ostap/comp — pull request #23 by julochrobak (2013-10-01 08:06:03+00:00)
Title: adding $ symbol for loop index, e.g. [i|i<-["a","b"],$i < 1]

I implemented the "$" operator to allow retrieving the index of a loop. Here are some examples:

$ bin/comp '[ i | i <- ["a", "b", "c"], $i < 1]'
[ "a" ]

$ bin/comp '[ {pos: $i, val: i} | i <- ["a", "b", "c"], $i > 0]'
[ { "pos": 1, "val": "b" }, { "pos": 2, "val": "c" } ]

$ bin/comp '[ {i, j} | i <- ["a", "b"], j <- [-1, -2], $i > 0 && $j < 1 ]'
[ { "i": "b", "j": -1 } ]

There are two things to discuss:
* I also tried to implement a function which would take the iteration variable and return it's index, for example:

[ i | i <- [1,2,3], index(i) < 1 ]

but I find this very complex to implement, because the "i" would have to change from an element of a list into kind of an object which contains also "iteration" information and the actual list element, and than the "index" function has to access the iteration part of this object, while everything else must access the element part:

[ i | i <- [1,2,3], i < 1]

may be there is a simple way to do it...

* the other question is, why are we actually implementing this? if we only want to allow to take just part of a list we can do it either either the haskell way:

head([1,2,3])	=>	1
tail([1,2,3])	=>	3
take(2, [1,2,3])	=>	[1,2]
drop(1, [1,2,3])	=>	[2,3]

or the golang way:

[1,2,3][:1]	=>	[1]
[1,2,3][2:]	=>	[3]
[1,2,3][0:2]	=>	[1,2]
[1,2,3][1:]	=>	[2,3]

I prefer to have both the `$` operator together with the golang way of getting a slice of a list.The `$` is valuable for all kinds of more complex calculations/filtering, e.g. take the elements only on the every second position in the list, can be put in the result to remember a position of an element in the list, and so on...