Perl Sq: bind & flatten
I implemented the bind function in my Perl Seq Module. bind is
a very useful function. For example here is flatten that I implemented with
it.
flatten
Flatten takes a sequence of sequences and returns a single sequence.
|
|
This is how a non-lazy Perl implemenation would look like:
|
|
Using it looks very similar.
|
|
This is how flatten is implemented in Seq.
|
|
$id is the id-function. It’s implementation:
|
|
I also could write.
|
|
bind is basically binding a value from left to right. Its like
assignment. It binds one value from the $iter sequence to the value $x.
The function we pass to, is executed for every value. But only when needed.
We could say that bind is like a lazy for-loop.
|
|
consider for as a function. It binds one value of @$iter to $x and executes
the function we pass with { ... }. But a for-loop does it in a non-lazy way.
It computes all values at once. Even if you only want to acces the first value of it.
Seq->flatten instead creates a new sequence without doing anything as long
you never ask it to evaluate.
Inside the lambda we passed to flatten we must return another sequence.
But bind will flatten the results to a single sequence.
This is why $id is passed. It returns the inner sequence as-is.
bind itself could be implemented with map and flatten.
|
|