haskell - 为什么这个函数签名不进行类型检查?

标签 haskell types typechecking

为什么不extractEither类型检查?

data MyEither a b = MyLeft a | MyRight b
                    deriving (Read, Show)

extractEither :: MyEither a b -> c
extractEither (MyLeft p) = p

编译器显示:
Couldn't match type `a' with `c'
  `a' is a rigid type variable bound by
      the type signature for extractEither :: MyEither a b -> c
      at /Users/tongmuchenxuan/playground/test.hs:5:1
  `c' is a rigid type variable bound by
      the type signature for extractEither :: MyEither a b -> c
      at /Users/tongmuchenxuan/playground/test.hs:5:1
In the expression: p
In an equation for `extractEither': extractEither (MyLeft p) = p

`c' 的通用性还不足以捕捉任何类型吗?

最佳答案

c是调用者希望函数返回的任何类型,即对于函数 f :: a -> c总是需要可以写 f x + 1 :: Int以及 putStr $ f x以及 main = f x .您的功能当然不允许。

你想要的是返回一个动态类型。 Haskell 故意不像其他一些语言那样容易地允许这样做,因为当返回的类型出乎意料时,它显然很容易导致运行时错误。有多种方法可以做到这一点,但哪种方法正确取决于您真正想要它的目的。你能给出一些背景吗?您的问题的最佳解决方案可能不是使用动态类型,而是更符合 Haskell 习惯的东西。

也许你想要的只是

extractEither :: MyEither a a -> a
extractEither (MyLeft p) = p
extractEither (MyRight p) = p

这要求“双方”的类型相同。

关于haskell - 为什么这个函数签名不进行类型检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11518338/

相关文章:

haskell - Euterpea异常:未找到MIDI输出设备

haskell - Hamlet 模板的编译时与运行时成本

types - Mathematica 是一种无类型语言吗?

javascript - (obj instanceof ObjectClass) 不起作用?

php - 强制 PHP 在未声明的变量上出错?在对象中?

compiler-construction - 类型检查器库

algorithm - 寻找矩阵中的最小元素 [[Int]]

haskell - Haskell 中的音频和信号处理

scala - Scala 中的多态方法 - 为什么允许这样做?

c++ - 有没有理由不使用单位强制类型?