gpt4 book ai didi

list - 如何使用 bind (>>=) 实现一个函数

转载 作者:行者123 更新时间:2023-12-03 10:00:06 24 4
gpt4 key购买 nike

我写了一个过滤函数:

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'

为了理解绑定(bind),我想使用绑定(bind)来实现它。我在想什么:

f p xs = xs >>= (\x xs -> if p x then x : f p xs else f p xs)

但是我得到这个错误:

* 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)

使用foldr成功做到了:

f p xs = foldr (\x xs -> if p x then x : f p xs else f p xs) [] xs

出了什么问题?

最佳答案

To understand bind, i want to implement this as bind.

这里没有绑定(bind)。在 do expression 的情况下添加绑定(bind).上面不是do-expression,所以这里没有bind。

但是你可以用 bind 写这个,比如:

f p xs = xs >>= \x -> if p x then [x] else []

但这不是原始函数的文字映射,我们在这里简单地使用instance Monad [] 实现。然而,您的 f 只是 filter :: (a -> Bool) -> [a] -> [a]在这里。

关于list - 如何使用 bind (>>=) 实现一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57109977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com