Search code examples
haskelltypestypeclassgeneric-type-argument

Haskell Type Classes in Type Alias declaration


I am trying to develop a module that performs different algorithms over a set of states by receiving the functions to manage them as paremeters. I was defining different type aliases to make it easier to implement; a simple example to understand this would be:

-- Function that expands a state
type Expand = State -> State
-- Function that evaluates a state
type Eval = State -> Float
-- Group of states
type Tree = [State]

And then I realized that I wanted State to be the alias of a type that is equatable: I really don't care if the user's states are (Int, Int), Float, or String as long as it's possible for him to implement the Expand and Eval functions and for me to compare two different states.

How can I generalize the type State to achieve this? The intuitive thing that comes to my mind is something like type State = (Eq a) => a but that is obviously not possible without an a in scope. Is there an easy way for me to declare functions that treat State as a black box?


Solution

  • You need to include the generic state as a type parameter.

    type Expand s = s -> s
    type Eval s   = s -> Float
    type Tree s   = [s]
    

    It's impossible to completely hide it, because e.g. Expand for an (Int, Int) state is a completely different type than for a String state.

    As for the Eq constraint. Typically, you would include that locally only in the specific function that requires the constraint.