Doubt about functions in Haskell

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 got the key concepts. So I started working with lists, and decided to reimplement some existing functions, just for practice purposes.

With this, I decided to make my version of the function reverse , which I called revert .

Her concept is simple. It receives a list, and returns it inverted. Its implementation is as follows:

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

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

However,Idecidedtodoanothertest,gettingtheresultofthefunctioninthesamevariablethatIpassedperparameter,asshownbelow:

It performs the function normally, but when I query the value of the variable x , it seems to enter some type of loop, and you must press Ctrl+C to cancel.

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

let y = revert x

would have worked, I've tested.

Why does this happen? Is it some quirk I did not get related to some concept of functional programming? I researched but found nothing. Maybe I have not found the correct terms to use in the search ...

    
asked by anonymous 21.03.2017 / 18:02

1 answer

2

After reading (and a question in the English OS), I have been able to understand why this is happening, and I will leave the explanation here to help anyone who might be interested.

All this happened because Haskell uses the concept of " lazy evaluation ." This means that no expression is evaluated when associated with a variable, but rather deferred until its result is required for other operations.

Even with this in mind, the code

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

Even though it looks perfectly normal. However, what happened so he could not show me the result of x was as follows:

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

Then, when I checked the value of x Haskell evaluated the value of the revert x operation, replacing it on the right, so it was:

revert (revert x)

and again:

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

And so, infinitely:)

    
21.03.2017 / 21:01