[英]Haskell function composition on Maybe
我在研究《 吹牛》中的 Haskell成語
-- split at whitespace
-- "hello world" -> ["hello","world"]
unfoldr (\b -> fmap (const . (second $ drop 1) . break (==' ') $ b) . listToMaybe $ b)
據我所知,文件夾應該是:
unfoldr :: (b -> Maybe (a,b)) -> b -> [a]
unfoldr f b =
case f b of
Just (a, new_b) -> a : unfoldr f new_b
Nothing -> []
所以fb必須在末尾什么都不輸出,對嗎?
所以我試圖理解f部分fmap (const . (second $ drop 1) . break (==' ') $ b) . listToMaybe $ b)
fmap (const . (second $ drop 1) . break (==' ') $ b) . listToMaybe $ b)
。
我有第二個想法,drop,break,listToMaybe。 但是我不知道為什么這樣的組合函數不能輸出Nothing。
Const
始終忽略第二個參數。 那么為什么要使用fmap (const . (second $ drop1) . break (==' ') $ b) . listToMaybe $ b
fmap (const . (second $ drop1) . break (==' ') $ b) . listToMaybe $ b
到底可以輸出什么?
(const . (second $ drop 1) . break (==' '))
為[Char] -> b -> ([Char], [Char])
這個復雜的函數只需要一個字符串(例如"one two three"
)和任何參數並返回("one", "two three")
。
因此, (const . (second $ drop 1) . break (==' ')) $ "one two three"
采用任何參數並返回("one", "two three")
。
fmap (const . (second $ drop 1) . break (==' ') $ b) . listToMaybe $ b
是相同的
fmap (const . (second $ drop 1) . break (==' ') $ b) $ listToMaybe b
例如,將函數fmapped
為Maybe
值,但是Maybe
實例的fmap
定義為:
instance Functor Maybe where
fmap _ Nothing = Nothing
fmap f (Just a) = Just (f a)
這意味着fmap
返回Nothing
如果a
在fmap fa
是Nothing
。
listToMaybe
返回Just
一個列表的第一個元素,或者Nothing
,如果該列表是空的。 這就是為什么
fmap (const . (second $ drop 1) . break (==' ') $ b) $ listToMaybe b
當b
為空列表時,將返回Nothing
。
代碼以混亂的方式編寫。 fmap (const xyz)
基本上將Maybe a
當作bool開關來濫用:如果它是Just _ᴡʜᴀᴛᴇᴠᴇʀ
,結果將是Just xyz
,而Nothing
只是簡單地傳遞了。 在列表為空的情況下, listToMaybe
可能Nothing
,這就是這種組合不能產生Nothing
。
所有這些的首選寫作風格是
unfoldr (\b -> listToMaybe b *> Just (second (drop 1) (break (==' ') b)))
或者實際上具有良好的老舊do
記號
unfoldr $ \b -> do
listToMaybe b
return . second (drop 1) $ break (==' ') b
但實際上,顯式模式匹配會更加清晰:
{-# LANGUAGE LambdaCase #-}
unfoldr $ \case
[] -> Nothing
b -> Just . second (drop 1) $ break (==' ') b
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.