代数接收项目位置的形态

问题描述

在变换器功能中需要给定项目的位置(索引或路径)时,使用哪种适当的态射(递归方案)?

一个简单的示例是将列表["foo","bar","qux"]转换为字符串"foo,bar,and qux"。需要知道当前元素的位置,以便知道何时插入and

解决方法

您需要使索引成为结构的一部分,以便它可用于递归方案。一种特殊的方法是定义一个 foldWithIndex 函数:

foldWithIndex :: (Foldable t,Num i) => (i -> a -> b -> b) -> b -> t a -> b
foldWithIndex f z t = snd $ foldr f' (0,z) t
    where
        f' z (i,x) = (i + 1,f i z x)

这个函数需要一个运算符来组合元素,同时考虑索引:

foldWithIndex combine "" ["foo","bar","qux"]
    where
        combine 0 s1 s2 = s1 ++ s2
        combine 1 s1 s2 = s1 ++ " and " ++ s2
        combine _ s1 s2 = s1 ++ "," ++ s2

结果为 "foo,bar and qux"

有关更通用的方法,请参阅 Data.Foldable.WithIndex,它提供了一个可折叠的类型类,同时也考虑了索引。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...