是否可以在 Haskell 中的两个不相关类型之间使用 case
表达式,如本例(不工作)代码所示:
data A = A
data B = B
f x = case x of
A -> 1
B -> 2
main = do
print $ test A
return ()
我知道我可以在这里使用Either
,但这段代码并不意味着要使用 - 我想深入学习 Haskell 类型系统并看看可以做什么。
最佳答案
A
和 B
是不同的类型。如果您想要一个可以接受多种类型值的函数,则需要一个类型类。
data A = A
data B = B
class F a where
f :: a -> Int
instance F A where
f _ = 1
instance F B where
f _ = 2
main = do
print $ f A
关于haskell - Haskell 中两个不相关类型之间的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18003300/