【发布时间】:2019-09-05 06:01:13
【问题描述】:
我正在做一些练习来练习我的 Haskell 技能。我的任务是自己用filter函数实现Haskell函数find。
我已经实现了没有filter 函数的find 函数(参见下面的代码块),但现在我的问题是用filter 函数实现它。
-- This is the `find` function without `filter` and it's working for me.
find1 e (x:xs)= if e x then x
else find1 e xs
-- This is the find function with the filter function
find2 e xs = filter e xs
find1的结果是对的
*Main> find1(>4)[1..10] Output : [5].
但是我用过滤器编写函数的实际任务给了我
*Main> find2(>4)[1..10] Output : [5,6,7,8,9,10].
我想要的find2 的结果是find1 的结果。
【问题讨论】:
-
find1需要空列表的基本情况吗?如果您只想要第一个结果,请使用head但知道它不安全(如果在列表中找不到匹配的元素,则会出错) -
看来 OP 正在寻找
filter的重新实现(而不是find)。他似乎用find的名字称呼filter。