我在 haskell 是什么意思?

0x6upsns  于 2023-03-03  发布在  其他
关注(0)|答案(2)|浏览(173)

你好,我刚开始学习Haskell从书Haskell编程从第一原则。这是从电话练习。请解释maybe [] id的用法。

reverset :: Phone -> Char ->[(Digit, Presses)]

 reverset (Phone buttons) c =
   maybe [] id $ find nonEmpty $ map (flip tapsOnButton c) buttons
   where
    nonEmpty [] = False
    nonEmpty _  = True

是空名单吗?

tyu7yeag

tyu7yeag1#

首先,我们来看一下maybe函数:

maybe :: b -> (a -> b) -> Maybe a -> b

如果maybe被应用两次,首先传递空列表([]),然后传递id函数,则会产生maybe [] id函数:

maybe [] id :: Maybe [a] -> [a]

当给定Maybe [a]值时,maybe [] id生成什么取决于使用哪个数据构造函数(JustNothing)生成此Maybe [a]值:

  • 如果是Just,给予此数据构造函数所取的值,即list。
  • 如果是Nothing,则生成空列表([])。

换句话说,maybe [] id等效于以下函数extractList

extractList :: Maybe [a] -> [a]
extractList (Just xs) = xs
extractList Nothing = []

粗略地说,它从可能失踪的语境中“提取”了一份清单;在这种情况下,如果缺少,则返回空列表。例如:

ghci> extractList (Just [1,2,3])
[1,2,3]
ghci> extractList Nothing
[]
ghci> extractList (Just [])
[]

注意,对于输入Just []Nothing,它产生相同的结果。

w6lpcovy

w6lpcovy2#

maybe :: b -> (a -> b) -> Maybe a -> b

引用自文件
maybe函数接受默认值、函数和Maybe值。如果Maybe值为Nothing,则函数返回默认值。否则,它将函数应用于Just中的值并返回结果。

相关问题