sanctuary-js / sanctuary

:see_no_evil: Refuge from unsafe JavaScript
https://sanctuary.js.org
MIT License
3.03k stars 94 forks source link

Is sanctuary lazy? #586

Closed uldaman closed 5 years ago

uldaman commented 5 years ago

That means that unless specifically told otherwise, it won't execute functions and calculate things until it's really forced to show you a result.

Say you have an immutable list of numbers xs = [1,2,3,4,5,6,7,8] and a function doubleMe which multiplies every element by 2 and then returns a new list.

If we wanted to multiply our list by 8 in an imperative language and did doubleMe(doubleMe(doubleMe(xs))), it would probably pass through the list once and make a copy and then return it. Then it would pass through the list another two times and return the result.

In a lazy language, calling doubleMe on a list without forcing it to show you the result ends up in the program sort of telling you "Yeah yeah, I'll do it later!". But once you want to see the result, the first doubleMe tells the second one it wants the result, now! The second one says that to the third one and the third one reluctantly gives back a doubled 1, which is a 2. The second one receives that and gives back 4 to the first one. The first one sees that and tells you the first element is 8. So it only does one pass through the list and only when you really need it.

That way when you want something from a lazy language you can just take some initial data and efficiently transform and mend it so it resembles what you want at the end.

syaiful6 commented 5 years ago

No, sanctuary not lazy. It still javascript, which not lazy language. The list defined in sanctuary is javascript's array. You probably can get lazy list by using generator, but do remember generator is not immutable..

davidchambers commented 5 years ago

As Syaiful mentioned, one can achieve lazy evaluation in a strictly evaluated language via generators, thunks, or transducers. Sanctuary promotes strictly evaluated data structures because we consider the lazy variants too complex for regular use (any lazy data structure which is compatible with Fantasy Land is compatible with Sanctuary, of course).