我有点不确定我正在尝试的实际名称是什么,创建折叠或变质似乎是它的名称。
我有以下折叠的数据结构:
type Order = [Int]
data Orders = Orders FilePath Order Order
type FoldOrders m o os = FilePath -> o -> o -> m os
type FoldOrder m o i = [i] -> m o
type FoldInt m i = Int -> m i
type Fold m os o i = (FoldOrders m o os, FoldOrder m o i, FoldInt m i)
foldOrders :: (Monad m) => Fold m os o i -> Orders -> m os
foldOrders (fos, fo, fi) (Orders orders1 orders2) = do o1 <- foldOrder orders1
o2 <- foldOrder orders2
fos o1 o2
where foldOrder order = do o <- mapM foldInt order
fo o
foldInt int = fi int
此折叠适用于例如此“实现”:
simpleWrite :: Fold IO () () ()
simpleWrite = (fos, fo, fi)
where fos _ _ = return ()
fo _ = return ()
fi i = putStrLn $ show i
使用此命令
foldOrders simpleWrite (Orders [1,2] [3,4])
1 2 3 4
它会像您期望的那样打印出来。
到目前为止一切顺利,但是..
当我想在遍历数据结构时“下推”一些信息(在这种情况下为文件路径),如下所示:
write :: Fold IO a b c
write = (fos, fo, fi)
where fos path fo1 fo2 = do _ <- fo1 path
_ <- fo2 path
return ()
fo fis path = do ios <- mapM (\x -> x path) fis
return ()
fi int path = appendFile path $ show int
我无法编译它。它返回此错误:
Couldn't match type `FilePath -> IO ()' with `IO c'
Expected type: FoldInt IO c
Actual type: Int -> FilePath -> IO ()
In the expression: fi
似乎您不能像这样返回部分单子函数,但这是为什么呢?我怎样才能让它工作?