首页 > 解决方案 > 如何在 zip 生成的列表上折叠 io 操作以打印 2 列?

问题描述

我已经看到了几个关于使用 foldl 和 IO 的问题,但似乎没有一个可以为我的案例提供解决方案。

我只是想输出两列数字。

0 256
1 256
2 256
...
256 256
0 255
1 255
2 255
3 255
4 255

我尝试了以下方法,但我只能打印一行而不是一整列:

zipMerge :: [a] -> [b] -> [(a,b)]
zipMerge [] _      = []
zipMerge _  []     = error "second list cannot be empty"
zipMerge (a:as) bs = (zip (replicate (length bs) a) bs) ++ (zipMerge as bs)

-- foldl :: (a -> b -> a) -> a -> [b] -> a
printPixel :: IO() -> (Int, Int) -> IO()
printPixel _ (i, j) = putStrLn (show i) ++ " " ++ (show j)

printPixels :: [(Int, Int)] -> IO()
printPixels colors = foldl printPixel (return ()) colors

printGradient :: IO()
printGradient = do
    putStrLn "255"
    let is = [0..256]
        js = [256,255..0]
    printPixels (zipMerge js is)

我究竟做错了什么 ?

标签: haskellfunctional-programmingiofold

解决方案


弃牌在这里绝对是矫枉过正。fold 的想法是在遍历列表时保留某种状态,但在您的情况下,没有要保留的状态:您只需要按顺序为每个元素执行效果,并且独立于其他元素。

为此,请使用mapM_

printPixel :: (Int, Int) -> IO()
printPixel (i, j) = putStrLn $ (show i) ++ " " ++ (show j)

printPixels :: [(Int, Int)] -> IO()
printPixels colors = mapM_ printPixel colors

或者它的 twinfor_,这是相同的东西,但是具有相反顺序的参数(和较弱的约束),它可以让您提供作为 lambda 表达式的效果,但没有括号,使其看起来几乎像forC 语言中的构造:

printPixels :: [(Int, Int)] -> IO()
printPixels colors = for_ colors $ \(i, j) -> putStrLn $ (show i) ++ " " ++ (show j)

推荐阅读