haskell - 在没有多余代码的情况下在 Haskell 中展开数据类型

标签 haskell coding-style

说我有

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 (在 PreludeData.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

同样, PreludeData.Eithereither :: (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/

相关文章:

java - 如何检查 Java 类成员顺序

coding-style - 什么时候违反单一职责原则是合理的?

haskell - 在这种情况下,GADT 如何影响类型推断?

oop - 纯函数式编程上下文中的面向对象编程?

debugging - 为什么是:sprint is showing WHNF even when i evaluate the variable?

Ruby风格问题: blocks or inheritance?

ruby - 设置未初始化的实例变量

haskell - 如何使用 xml-conduit 游标接口(interface)从大型 XML 文件(大约 30G)中提取信息

haskell - 为什么这些 Haskell 函数的推断类型不完全相同?

c - 旧式 C 函数声明