如何定义具有不同类型输入和输出的函数?

时间:2016-10-16 01:22:22

标签: haskell

我尝试了以下代码:

data InputType = NumType Int Int | StrType String String
data OutputType = Either Int String
add' :: InputType -> InputType -> OutputType
add' (NumType a b) = a + b
add' (StrType a b) = a ++ b

但失败了:(

2 个答案:

答案 0 :(得分:5)

您对OutputType的声明并未指明它可以是Int还是String;相反,您创建了一个新的,需要Int 一个String。您的数据构建器Either恰好与类型构造函数Either具有相同的名称。

我认为你的意思是

type OutputType = Either Int String

在这种情况下,如果使用正确的构造函数,则可以定义函数

add' :: InputType -> OutputType
add' (NumType a b) = Left (a + b)
add' (StrType a b) = Right (a ++ b)

答案 1 :(得分:1)

您可以使用GADT在值级别表示您获得的输入类型:

{-# LANGUAGE GADTs #-}

module Add where

data SType a where
  SString :: SType String
  SInt    :: SType Int

add :: SType a -> a -> a -> a
add SString = (++)
add SInt    = (+)

我致电GADT SType,因为它是singleton type

相关问题