1

In order to obtain honors credit for a course, I have been tasked with recreating an assignment we completed in ML (using the SMLNJ implementation), but using haskell instead. The goal here is to create a datatype environment that binds values to strings.

The type declaration in ML is:

type 'a Env = string -> 'a;

The basic functions created are env_new() which creates an empty environment, and env_bind() which takes an environment, string, and value and binds the string to the value while returning a new environment.

Test showing the ML functionality are as follows:

- val e1 = env_new() : int Env;
val e1 = fn : int Env
- val e2 = env_bind e1 "a" 100;
val e2 = fn : int Env
- val e3 = env_bind e2 "b" 200;
val e3 = fn : int Env
- e1 "a";
uncaught exception NameNotBound
- e2 "a";
val it = 100 : int
- e3 "a";
val it = 100 : int

My current declaration of this type in Haskell and related functions is:

data Env a = Env String a

envNew :: a -> Env a
envNew a = Env a

envBind :: Env a -> String -> a -> Env a
envBind environment name value = Env name value

I am having a very hard time figuring out the proper syntax for these definitions. Please respond with any hints that would help me make progress on this. Keeping in mind that this is for honors credit - I do not expect any full solutions but simply some assistance (not that I would reject solutions).

Benjamin Hodgson
  • 42,952
  • 15
  • 108
  • 157
smallmax55
  • 21
  • 1
  • Don't confuse the type with its data constructor. For example, `Env "Foo" "Bar" ` creates a value of type `Env String`, while (assuming 9 is an `Int` for purpose of this example) `Env "Bar" 9` creates a value of type `Env Int`. Consider how this affects your attempt at defining `envNew`. – chepner Mar 31 '16 at 14:10
  • `type Env a = String -> a` was a bit too obvious, I guess. (Your Haskell type would correspond to `datatype 'a Env = Env of string * 'a` in SML.) – molbdnilo Apr 01 '16 at 09:11

1 Answers1

3
data Env a = Env String a

This is not the same type as in ML: there's no arrow above. You want

data Env a = Env (String -> a)

Then,

envNew :: a -> Env a
envNew a = Env a

this has not the same type as in ML! Fix that.

Also,

envBind :: Env a -> String -> a -> Env a
envBind environment name value = Env name value

make little sense: it does not even use the environment. Start from the definition in ML you have, and try to mimic that one.

chi
  • 111,837
  • 3
  • 133
  • 218