I was learning some new Haskell today, when I tried something in ghci. It basically boiled down to this:
Prelude> let x = 6
Prelude> x
6
Prelude> let y = show x
Prelude> y
"6"
Prelude> let x = show x
Prelude> x
"\"\\\"\\\\\\\"\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\" --(repeats)
So can ghci not self-reference in assignment? I feel like it's akin to i = i++;
in C, or trying to reference previous assignments of a let
(not let*
) in Scheme. Is there anyway to do this, or should I just use the easier let y = show x
?
Definitions in Haskell are recursive by default. So the definition you made for x
refers to the very same x
, which is the reason for the very long string you are seeing, because x
is defined to a String
that is the result of calling show
on itself, so you keep seeing the opening quotes for showing a string, and then those opening quotes escaped, and so on.
These kinds of definitions can be surprisingly useful. For example if you write:
let fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
you can define the Fibonacci sequence in terms of itself as an infinite list.
Then you can do something like take 10 fibs
to just see the first 10 elements.
It's self referencing indeed! It's trying to solve the equation
x = show x
Since show
returns a string Haskell knows that x
begins like "\""
and that's enough to guess the second character, which is enough for the third which is enough for the fourth...
And so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With