V0l*_*337 4 monads haskell list
我写了一个过滤功能:
f :: (a -> Bool) -> [a] -> [a]
f p xs = case xs of
[] -> []
x : xs' -> if p x
then x : f p xs'
else f p xs'
Run Code Online (Sandbox Code Playgroud)
要了解绑定,我想使用绑定实现此功能。我在想什么:
f p xs = xs >>= (\x xs -> if p x then x : f p xs else f p xs)
Run Code Online (Sandbox Code Playgroud)
但是我得到这个错误:
* Couldn't match expected type `[a]' with actual type `[a] -> [a]'
* The lambda expression `\ x xs -> ...' has two arguments,
but its type `a -> [a]' has only one
In the second argument of `(>>=)', namely
`(\ x xs -> if p x then x : f p xs else f p xs)'
In the expression:
xs >>= (\ x xs -> if p x then x : f p xs else f p xs)
* Relevant bindings include
xs :: [a] (bound at <interactive>:104:5)
p :: a -> Bool (bound at <interactive>:104:3)
f :: (a -> Bool) -> [a] -> [a] (bound at <interactive>:104:1)
Run Code Online (Sandbox Code Playgroud)
使用foldr以下命令成功完成:
f p xs = foldr (\x xs -> if p x then x : f p xs else f p xs) [] xs
Run Code Online (Sandbox Code Playgroud)
怎么了
要了解绑定,我想将其实现为绑定。
这里没有绑定。如果是do表达式,则添加绑定。上面不是do表达式,因此这里没有绑定。
但是,您可以使用bind编写此代码,例如:
f p xs = xs >>= \x -> if p x then [x] else []Run Code Online (Sandbox Code Playgroud)
但这不是原始函数的文字映射,我们仅在instance Monad []此处使用实现。不过,您f就filter :: (a -> Bool) -> [a] -> [a]在这里。