给予(无家庭作业):
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),我如何继续使它成为递归的?但我不明白这一节:getFirst . foldMap (\ x -> First (
有人能解释一下这句话吗?
发布于 2017-05-27 09:25:11
如果您正在学习Haskell,我建议您暂时忘掉Foldable和First,因为它们涉及比实现first'所需的更高级的主题。
作为提示,请尝试计算一个简单的递归定义,如下所示:
-- Finds the first element of a list that satisfies a given condition.
first' :: (a -> Bool) -> [a] -> Maybe a
first' p [] = ...
first' p (x:xs) = ...
where
-- the first in the tail xs
rec = first' p xs想想看:
p应该是什么?rec是尾列表xs中第一个令人满意的p,那么如何表示完整列表x:xs中的第一个令人满意的p?你可以用如果-然后-其他的。发布于 2017-05-27 12:48:33
但我不明白这一节: getFirst。foldMap (\ x -> First )
首先,让我们看一下First,例如在李亚赫中。它是一个幺半群,定义如下:
newtype First a = First { getFirst :: Maybe a }
deriving (Eq, Ord, Read, Show) 和
instance Monoid (First a) where
mempty = First Nothing
First (Just x) `mappend` _ = First (Just x)
First Nothing `mappend` x = x 从直觉上看,这意味着:
First of NothingFirst的Just (如果有一个,则为First Nothing )。因此,顾名思义,它是一个“记录”它遇到的第一个Just的单子。
如果你看一下foldMap,它就会对可折叠的所有东西进行折叠,这是不足为奇的。那么,直觉地说,如果折叠包含一些Just,那么foldMap的结果就是First这样的Just;否则,它就是First Nothing。
现在,您希望将这个First的值提取到一个Maybe中。这就是getFirst所做的。
整个行由getFirst和foldMap组成。
https://stackoverflow.com/questions/44214805
复制相似问题