说我有
x = Just 2
有没有办法(最好是内置机制/函数)在单个语句中使用 x,如果它是 Just,那么 2 会自动解包并使用,如果它是 Nothing,则会引发异常?
那是,
(f x) + 2 == 4
如果 x == Just 2
, 如果 x == Nothing
则引发异常.
最佳答案
Data.Maybe.fromJust
已经被其他答案提到:
fromJust :: Maybe a -> a
fromJust Nothing = error "Maybe.fromJust: Nothing"
fromJust (Just x) = x
还有
maybe
(在 Prelude
和 Data.Maybe
中都可以找到):maybe :: b -> (a -> b) -> Maybe a -> b
maybe n _ Nothing = n
maybe _ f (Just x) = f x
fromJust
可以使用 maybe
编写:fromJust = maybe (error "Maybe.fromJust: Nothing") id
如您所见,
maybe
允许您灵活地处理这两种情况,而无需模式匹配:\x -> maybe 0 (+ 2) x -- Nothing -> 0, Just 2 -> 4
同样,
Prelude
和 Data.Either
有 either :: (a -> c) -> (b -> c) -> Either a b -> c
:\x -> either (subtract 1) (* 2) x -- Left 5 -> 4, Right 3 -> 6
如果定义数据类型
data MyDataType
= TypeA { foo :: Int, bar :: String }
| TypeB { foo :: Int, baz :: () }
| TypeC { bar :: String, baz :: () }
像这样,你最终得到了访问器的部分函数。
foo :: MyDataType -> Int
bar :: MyDataType -> String
baz :: MyDataType -> ()
它们被称为部分函数,而不是总函数,因为它们只返回其输入子集的结果。
foo (TypeA { foo = 15, bar = "hello!" }) -- 15
bar (TypeB { foo = 12345679, baz = () }) -- error
关于haskell - 在没有多余代码的情况下在 Haskell 中展开数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2100069/