gongqj
gongqj

Reputation: 782

How to define a function with different types of input and output?

I tried the following code:

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

But failed :(

Upvotes: 1

Views: 1929

Answers (2)

gallais
gallais

Reputation: 12123

You could use a GADT to represent at the value level the type of the input you're getting:

{-# 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    = (+)

I called the GADT SType because it's a singleton type.

Upvotes: 1

chepner
chepner

Reputation: 532268

Your declaration of OutputType does not specify that it can be either an Int or a String; rather, you have created a new pair that requires both an Int and a String. Your data constuctor Either just happens to have the same name as the type constructor Either.

I think you meant

type OutputType = Either Int String

in which case you can then define your function if you use the correct constructors

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

Upvotes: 4

Related Questions