給出(無家庭作業):哈斯克爾遞歸查找功能和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