Tuesday, 10 September 2013

Is it possible to define an array recursively in Haskell?

Is it possible to define an array recursively in Haskell?

In several programming languages (including JavaScript, Python, and Ruby),
it's possible to place an array inside itself. However, I tried doing this
Haskell, and it wouldn't compile properly:
--anArray!!0!!0!!1 should be 1, since anArray is recursively defined: the
first element of anArray is anArray.
main = putStrLn $ show $ anArray!!0!!0!!1
anArray = [anArray, 1]
This program did not work as I expected: instead of printing 1, it
produced this compiler error:
[1 of 1] Compiling Main ( prog.hs, prog.o )
prog.hs:3:12:
Occurs check: cannot construct the infinite type: t0 = [t0]
In the expression: anArray
In the expression: [anArray, 1]
In an equation for `anArray': anArray = [anArray, 1]
Is it possible to put an array inside itself in Haskell, as I'm attempting
to do here?

No comments:

Post a Comment