Doubt about duties in Haskell

Asked

Viewed 149 times

3

I decided to dive into the world of functional programming recently, and was introduced to the Haskell language. I started researching how language works, and soon I was able to get the main concepts. So I started working with lists, and decided to reimplement some existing functions, just for practice purposes.

With that, I decided to make my version of the function reverse, who I called revert.

Its concept is simple. It takes a list, and returns it reversed. Its implementation is the following:

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

It worked, as you can see in the image below:

inserir a descrição da imagem aqui

However, I decided to do another test, receiving the function result in the same variable that I passed by parameter, as shown below:

inserir a descrição da imagem aqui

It performs the function normally, but when I refer to the variable value x, it seems to enter some kind of loop, and it is necessary to tighten Ctrl+C to cancel.

Detail, it only happens if I receive in the same variable I passed by parameter. If I had done:

let y = revert x

would have worked, I tested.

Why does this happen? Is it some peculiarity that I didn’t get related to some concept of functional programming? I researched but found nothing. Maybe I haven’t found the right terms to use in the search...

  • 1

    It reminded me of the subject of LP, the suffering rs +1 good question

1 answer

2


After reading (and a question in the OS in English), I was able to understand why this happened, and I will leave the explanation here to contribute to whom it may interest.

All this happened because Haskell uses the concept of "lazy assessment". This means that no expression is evaluated when associated with a variable, and yes postponed until its output is required for other operations.

Even with that in mind, the code

let x = [0..10]
x = revert x

it still seems perfectly normal. However, what happened so that he could not show me the result of x was the following:

on the line x = revert x , the expression revert xwas associated with the variable x, but as an expression, not as a result. That is, that expression was not evaluated.

So when I consulted the value of x the Haskell evaluated the value of the transaction revert x, replacing to the right, so that was:

revert (revert x)

and again:

revert (revert (revert ... x)..)

And so, endlessly :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.