if I try > fst(a, b)
where a
, b
are undefined, I get the error that b
is undefined. Even on trying snd(a, b)
it is b
that causes the error first. I have a background in imperative programming. I am wondering if this is some kind of laziness that I don't understand.
I think FUZxxl's comment is absolutely correct. When I type into Hugs' repl:
Hugs> fst(a,b)
ERROR - Undefined variable "b"
Hugs> snd(a,b)
ERROR - Undefined variable "b"
This isn't a lazy/eager evaluation thing -- when Hugs checks to make sure that fst(a,b)
is valid Haskell code, it notices that a
and b
aren't defined. Those two letters don't have special meanings in Haskell, they're variables like in any other language!
It's like in Java going:
System.out.println(a);
And never saying what a
is! You'd instead write something like:
String a = "Hello world."
System.out.println(a);
To remedy this, you can either define a
and b
in a let statement, like:
>let (a,b) = (1,2) in fst(a,b)
or
>let tup = (1,2) in fst tup
or
>let a=1;b=2 in fst(a,b)
or a where statement
>fst(a,b) where a=1;b=2
etc.
Alternatively, define in some file called whatever (for example, "TestTuple.hs")
a = 1
b = 2
and in Hugs, go:
>:load TestTuple.hs
>fst(a,b)
1
Although you note that you are using Hugs, just for reference, in GHCi, you can also define variables in the REPL like this:
>let a = 1
>let b = 2
>fst(a,b)
1
>snd(a,b)
2