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?
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With