为什么不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/