Den*_*nis 0 syntax monads haskell
我已经了解了do-notation.我现在想开发一个转换列表的函数.
我希望它表现得像这样:
?> transform 42 [1, 2, 3, 4, 5, 6]
[1, 42, 2, 42, 3, 42, 4, 42, 5, 42, 6, 42]
Run Code Online (Sandbox Code Playgroud)
我目前的代码是:
transform :: a -> [a] -> [a]
transform new_number xs = do x <- xs
return x
return new_number
Run Code Online (Sandbox Code Playgroud)
......我的结果是:
?> transform 42 [1, 2, 3]
[42,42,42]
Run Code Online (Sandbox Code Playgroud)
我怎样才能解决这个问题?
return在Haskell中不像命令式语言那样工作.写两个returns在这里是没有意义的,因为第二个'覆盖'第一个.
do-notation专门用于处理Monads,因此您的类型正确,但您使用的函数不正确.这就是我这样做的方式:
transform :: a -> [a] -> [a]
transform new xs = do
x <- xs
[x,new]
Run Code Online (Sandbox Code Playgroud)
这是有效的原因是我用类型的东西结束我的表达[a].你不一定要用return!
do在这里使用-notation有点令人困惑,所以使用它可能更好concatMap :: (a -> [b]) -> [a] -> [b]:
transform new xs = concatMap (\x -> [x,new]) xs
Run Code Online (Sandbox Code Playgroud)