Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laziness and function composition (haskell, erlang)

Can someone please explain or give some resources on how function composition works in relation to laziness?

For example how does filter (/='W') . map toUpper $ "justaword" work in Haskell compared to it's counterpart in erlang which is not lazy?

like image 671
Adi Avatar asked Jan 27 '12 10:01

Adi


People also ask

What is laziness in Haskell?

Lazy evaluation is a method to evaluate a Haskell program. It means that expressions are not evaluated when they are bound to variables, but their evaluation is deferred until their results are needed by other computations.

What is the main differences between cloud Haskell and Erlang?

Haskell has more concise syntax, better suited for traditional programming competitions, whereas Erlang is successful, but its syntax is not easy to get on with. Haskell does not have brilliance when it comes to concurrency, whereas Erlang is suitable for the concurrency-based system.

Why is lazy evaluation useful in Haskell?

Lazy evaluation has advantages and disadvantages. It's easy to see some of the advantages. First, you get the computational benefit that any code you don't absolutely need is never computed. Another benefit is that you can define and use interesting structures such as an infinite list.


1 Answers

Every time another character is demanded (or notification of end), the next character - if any - is mapped to uppercase, that is compared to 'W', delivered if unequal.

filter (/= 'W') . map toUpper $ "justaword"
~> filter (/= 'W') (toUpper 'j' : map toUpper "ustaword")
~> filter (/= 'W') ('J' : map toUpper "ustaword")
~> 'J' : filter (/= 'W') (map toUpper "ustaword")

Now the first character is available, so for queries like null or functions like take 1, no further work is done. If more characters are demanded by the consumer, they will be produced one by one until the end of the string is reached.

Example:

Prelude Data.Char> take 10 . filter (/= 'W') . map toUpper $ repeat 't'
"TTTTTTTTTT"

repeat produces an infinite list, but as long as only a finite part is consumed, the computation finishes in finite time. However, take 10 . filter (/= 'W') . map toUpper $ repeat 'w' would not terminate, since none of the produced characters passes the filter to reach the take 10.

like image 121
Daniel Fischer Avatar answered Nov 16 '22 00:11

Daniel Fischer