gpt4 book ai didi

haskell - 删除列表中满足条件的第一个值

转载 作者:行者123 更新时间:2023-12-02 12:07:47 26 4
gpt4 key购买 nike

我正在努力解决这个问题。该函数有两个参数。第一个是返回 bool 值的函数,第二个是数字列表。该函数应该删除第二个参数中的第一个值,该值在使用第一个参数运行时返回 true。还有第二个函数,它执行相同的操作,只不过它删除满足它的最后一个值,而不是第一个。我相当确定我已经掌握了逻辑,因为我用另一种语言测试了它并且它有效,我唯一的问题是将它翻译成 Haskell 语法。这是我所拥有的:

removeFirst :: (t -> Bool) -> [t] -> [t]
removeFirst p xs = []
removeFirst p xs
| p y = ys
| otherwise = y:removeFirst p ys
where
y:ys = xs

removeLast :: (t -> Bool) -> [t] -> [t]
removeLast p xs = []
removeLast p xs = reverse ( removeFirst p ( reverse xs ) )

我跑了:

removeFirst even [1..10]

但是我得到的是 [],而不是预期的 [1,3,4,5,6,7,8,9,10]。我做错了什么?

最佳答案

removeFirst p xs = []

这总是返回空列表并且它匹配所有参数。我想你的意思是这个。

removeFirst _ [] = []

关于haskell - 删除列表中满足条件的第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28681339/

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