我有以下类型类
class MyClass c where
aFunction :: c -> Bool
以及两种不同数据类型的两个实例
data MyDataType1 = MyDataType1
instance MyClass MyDataType1 where
aFunction c = True
data MyDataType2 = MyDataType2
instance MyClass MyDataType2 where
aFunction c = False
我想编写一个函数,该函数接受类型类 MyClass 的两个参数(可能是相同的数据类型或可能不同并返回其中一个。我正在努力为此制定类型签名,我想我可能会采取错误的方法。
这是正确的吗?如果不是,我应该改用什么?
chooseOne :: (MyClass a, MyClass b) => a -> b -> ?
chooseOne x y = if (aFunction x) then x else y
最佳答案
你的返回值可以是任何一种类型,所以编译器会提示,除非你对两者使用相同的类型,给出
chooseOne :: (MyClass a, MyClass a) => a -> a -> a
这不是你的意思。
要将两种可能不同的类型合并为一种,您可以使用 Either 数据类型:
data Either a b = Left a | Right b
所以你会有
chooseOne :: (MyClass a, MyClass b) => a -> b -> Either a b
chooseOne x y = if (aFunction x) then Right x else Left y
但我宁愿这样写
chooseOne :: (MyClass a, MyClass b) => a -> b -> Either a b
chooseOne x y | aFunction x = Right x
| otherwise = Left y
关于haskell - 返回相同类型类的两种类型之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16500040/