gpt4 book ai didi

haskell - 与仅包含一对的模式匹配

转载 作者:行者123 更新时间:2023-12-02 17:31:42 25 4
gpt4 key购买 nike

我正在尝试 Haskell,我想知道为什么我无法与包含一对的 Just 进行匹配。我对这种语言几乎没有经验,我完全迷失了。

f :: Int -> Maybe (Int, [Int])
f 100 = Nothing
f x = Just (x,[x])

g :: Int -> Maybe Int
g x
| u==Nothing = Nothing
| u==(Just (r,s)) = Just r
where
u=f x

那么这段代码有什么问题呢? GHC 表示 rs 不在范围内。

最佳答案

如果你想在守卫中进行模式匹配,你必须使用 pattern guard :

g :: Int -> Maybe Int
g x
| Just (r,_) <- u = Just r
| otherwise = Nothing
where
u = f x

毕竟,(==)是一个常规函数,需要两边都有值才能使用它。由于 u == Just (r,s) 中不知道 rs,因此编译器会向您提供错误消息。

顺便说一句,如果值为 NothingJust (h x),则采用 Maybe 并返回 Nothing > 对于函数 hJust x 来说非常常见,它形成了一个模式:fmap。你可以写

g :: Int -> Maybe Int
g x = fmap fst (f x)

关于haskell - 与仅包含一对的模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42198779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com