Home > Back-end >  Mapping variable names to value in predefined types in Haskell
Mapping variable names to value in predefined types in Haskell

Time:11-05

I have defined two types as shown below with Vname representing a variable name as a string and Val representing an integer value:

type Vname = String
type Val = Int
type State = ...

with the type State still to be defined (I am also not sure if I have done Vname and Val correctly either). State has to be a mapping between Vname and Val and I assume it would be along the lines of:

type State = Vname->Val

but I am really not sure. Any clarification on this would be helpful.

it is for an implementation of a low-level machine with commands to operate a stack, with Vname being the variable name of the number you are putting onto the stack and Val being the value. The types are there for custom ghci input names.

Thank you.

CodePudding user response:

To be precise, you've defined two type aliases, not two types.

State could be a function:

type State = Vname -> Maybe Val

foo :: State
foo "x" = Just 3
foo "y" = Just 5
-- etc
foo _ = Nothing

or it could be a list of name/value pairs.

type State' = [(Vname, Val)]

foo' :: State'
foo' = [("x", 3), ("y", 5)]

Note that foo and \x -> lookup x foo' (or flip lookup foo') are basically the same function.

Which you choose depends mostly on how you plan to use a value of type State. Sometimes the function will be more convenient, other times the list of pairs. I might lean toward the list, as it's easier to create a functional form (using lookup, as shown above) from a list than it is to create a list from a function (as that requires a list of values to apply the function to).

  • Related