Quantcast
Channel: Hacker News 50
Viewing all articles
Browse latest Browse all 9433

Haskell-like list comprehensions in Ruby

$
0
0

Comments:"Haskell-like list comprehensions in Ruby"

URL:https://gist.github.com/andkerosine/3356675


$stack,$draws=[],{}

 

defmethod_missing*args

returnifargs[0][/^to_/]

$stack<<args.map{|a|aor$stack.pop}

$draws[$stack.pop(2)[0][0]]=args[1]ifargs[0]==:<

end

 

classArray

def+@

$stack.flatten!

keys=$draws.keys&$stack

draws=$draws.values_at*keys

 

comp=draws.shift.product(*draws).mapdo|draw|

$stack.map{|s|draw[keys.indexs]rescues}.reducedo|val,cur|

op=Symbol===cur?[:send,:method][val.method(cur).arity]::call

val.sendop,cur

end

end

 

$stack,$draws=[],{}

Symbol===last?comp.select(&pop):comp

end

 

def-@

casemap(&:class).indexRange

when0thenfirst.to_a

when1then[first]+last.step(last.min.ord-first.ord).to_a

elseself

end

end

end

 

foo=+[x*y|x<-[1..3],y<-[4..6]]

# [4, 5, 6, 8, 10, 12, 12, 15, 18]

 

bar=+[a+b|a<-['n','p'..'t'],b<-%w[a i u e o]]

# ["na", "ni", "nu", "ne", "no", "pa", "pi", "pu", "pe", "po", "ra", "ri", "ru", "re", "ro", "ta", "ti", "tu", "te", "to"]

 

baz=+[i**2/3|i<-[3,6..100],:even?]

# [12, 48, 108, 192, 300, 432, 588, 768, 972, 1200, 1452, 1728, 2028, 2352, 2700, 3072]

 

quux=+[s.size.divmod(2)|s<-%w[Please do not actually use this.]]

# [[3, 0], [1, 0], [1, 1], [4, 0], [1, 1], [2, 1]]


Viewing all articles
Browse latest Browse all 9433

Trending Articles