Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ghci self-referencing assignment

Tags:

haskell

ghci

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?

like image 575
charmlessCoin Avatar asked Jan 19 '14 22:01

charmlessCoin


2 Answers

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.

like image 167
GS - Apologise to Monica Avatar answered Sep 22 '22 05:09

GS - Apologise to Monica


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.

like image 40
J. Abrahamson Avatar answered Sep 23 '22 05:09

J. Abrahamson