Haskell type signature with multiple class constraints
Asked Answered
S

1

34

How can I have multiple class constraints, so if A is an Eq and B is a Num, I could say either

f :: Eq a => a -> b`

or

f :: Num b => a -> b

So, how can I have Eq a => and Num b => at the same time?

  • f :: Eq a => Num b => a -> b,
  • f :: Eq a -> Num b => a -> b, and
  • f :: Eq a, Num b => a -> b

didn't do what I wanted.

Superannuated answered 19/6, 2012 at 3:3 Comment(0)
D
66

They're usually called class constraints, as Eq and Num are called type-classes.

How about this?

f :: (Eq a, Num b) => a -> b

The parentheses are significant.

Duluth answered 19/6, 2012 at 3:10 Comment(2)
Aha! Thank you. Do these parentheses with a comma cause a higher-level tuple of some kind, or is this another meaning of parentheses?Superannuated
@Andrew actually they do (now) although you probably should not be worrying yourself about such things just yet. Normall Haskell types have kind (type of type) *, so the tuple type has kind * -> * -> *. In recent versions of GHC there is a new kind Constraint such that Eq :: * -> Constraint, and tuples have been promoted to this new kind.Humo

© 2022 - 2024 — McMap. All rights reserved.