给出(无家庭作业):哈斯克尔递归查找功能和Data.Foldable找到解释
first' :: (a -> Bool) -> [a] -> Maybe a
-- Finds the first element of a list that satisfies a given condition.
我得到这个语句后丢失:
if p x then Just x else Nothing)
如何继续使它递归?我发现这一点:
-- | The 'find' function takes a predicate and a structure and returns -- the leftmost element of the structure matching the predicate, or -- 'Nothing' if there is no such element. find :: Foldable t => (a -> Bool) -> t a -> Maybe a find p = getFirst . foldMap (\ x -> First (if p x then Just x else Nothing))
但我不明白这个部分:getFirst . foldMap (\ x -> First (
有人能解释一下这个说法?
谢谢您的明确解释,但我仍然有我的原始问题: 在“正常”递归函数中,只要条件未满足(result = Nothing),则迭代;或者如果条件满足,结果=只是x)我们停下来。 这里我需要三个条件:没有,只要x,继续迭代。 – Atir
谢谢您的明确解释,但我仍然有我的原始问题: 这是Maybe语句让我困惑。 在“正常”递归函数中,只要条件不满足(result = Nothing),或者条件满足(result = Just x),我们就停止。 这里我需要三个条件:Nothing,只需x并继续迭代。 我该如何克服这个困难? – Atir
@Atir如果列表是空的,你知道没有满足'p'的值,所以你可以返回Nothing。否则,你可以检查'p x':它持有,你可以返回'只需x',否则,你会与列表的其余部分递归。 – chi