Artur Trapp
Artur Trapp

Reputation: 434

What is wrong in this Haskell function?

I decided to dive in functional programming world recently, and a friend told me about Haskell. I started my own researches on the language particularity and soon I got the main concepts. Then, I started working with lists and decided to rewrite some existent functions, just to practice.

I made my version of the reverse function, and called it revert. The function is defined as below:

revert :: [a] -> [a]
revert [] = []
revert a = revert (tail a) ++ [head a]

It works perfectly for me, as you can see in the image:

works

But then, I decided to make another test, receiving the result of the revert function on the same variable that I passed as a parameter, as you can see below:

enter image description here

It seems to execute the function normally, but when I check the value of x, it looks like it goes into a loop, and I need to interrupt the operation.

If I set the value on another variable, it works perfectly:

let y = revert x

Why does it happen? Is it some concept of functional programming that I am missing? Or some peculiarity with Haskell? I did some googling but was not able to get to an answer

PS: Sorry for the bad english

Upvotes: 2

Views: 148

Answers (1)

Ingo
Ingo

Reputation: 36339

You're defining

x = revert x

So, substituting on the right, this gives

x = revert (revert x)

And so on. Another example would be

a = a + 1

To find out what a is, we need to evaluate the right hand side of the definition.

a = (a + 1) + 1
a = ((a+1)+1) + 1

And so on.

Bootom line: Haskell's = is very different from = in languages like C#, where it means assignment. In Haskell it means is defined as and this means we can substitute any occurance of an identifier with its definition without changing the meaning of the program. This is called referential transpareny.

Upvotes: 7

Related Questions