Eleftherios
Eleftherios

Reputation: 3

Haskell function definition

I'm having trouble defining a function in Haskell. What I want to do is input a variable of type EnvV and one of type Store and return a State type variable:

type Variable = String
type Z = Integer
type T = Bool
type State = Variable -> Z
type Location = Z
type Store = Location -> Z
type EnvV = Variable -> Location

search :: EnvV -> Store -> State
search envV store = envV(store)  

Upvotes: 0

Views: 134

Answers (3)

Sibi
Sibi

Reputation: 48766

Try matching the types:

You have EnvV which is Variable -> Location and Store which is Location -> Z

And you want the output of State which is Variable -> Z

Can you see the connection between them ? You have to eliminate Location between them.

search :: EnvV -> Store -> State
search envV store = \x -> store (envV x)

Since you want Variable in the output, introduce x which denotes that. Then apply it to envV which will give you Location . Now apply that to store which will give Z. This will give you a type of Variable -> Z which is expected by you.

This can be written more concisely:

search :: EnvV -> Store -> State
search envV store = store . envV

Upvotes: 0

chi
chi

Reputation: 116174

The type

search :: EnvV -> Store -> State

means

search :: EnvV -> Store -> Variable -> Z

Hence, you can use

search envV store var = store (envV var)

because envV var is a Location, which is then applied to store to produce a Z.

Note that the following code is correct, even if it's a bit puzzling

search :: EnvV -> Store -> State
search envV store var = store (envV var)

It's puzzling because its type shows two arguments, when the code below takes three. Equivalently, the code above is more commonly written as

search :: EnvV -> Store -> State
search envV store = \var -> store (envV var)

so that even in the definition we can find two arguments, and a result value which is actually a function of type State which maps every variable var into its value.

The code above can then further be simplified to use the function composition operator ., as @ChrisMartin already showed.

Upvotes: 0

Chris Martin
Chris Martin

Reputation: 30756

Your question seems to simplify to:

type State = String -> Integer
type Store = Integer -> Integer

search :: State -> Store -> State

There are an infinite number of ways to implement this, but I'm going to guess that the result you want is simply the composition of the two functions.

search state store = store . state

Or more simply

search = flip (.)

Upvotes: 1

Related Questions