Module: Enumerable

Defined in:
lib/functions/prelude_enumerable/enumerable.rb

Instance Method Summary collapse

Instance Method Details

#counted_setObject



20
21
22
# File 'lib/functions/prelude_enumerable/enumerable.rb', line 20

def counted_set 
  self.inject( Hash.new(0) ) { |h,e| h[e] += 1; h } 
end

#grouped_by(&f) ⇒ Object



24
25
26
# File 'lib/functions/prelude_enumerable/enumerable.rb', line 24

def grouped_by &f
  self.group_by(&f).values
end

#interleave(ys) ⇒ Object



28
29
30
# File 'lib/functions/prelude_enumerable/enumerable.rb', line 28

def interleave ys
  self.zip(ys).flatten.compact
end

#merge(ys, &f) ⇒ Object

merges two ordered lists by a function f that compares the values if no function is given the values are compared by the “<” operator



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/functions/prelude_enumerable/enumerable.rb', line 34

def merge ys, &f

  return self.dup if ys.empty?
  return ys.dup if self.empty?

  x, *xt = self
  y, *yt = ys

  return ys.merge(xt, &f) >> x if ( f.nil? ? x < y : f.(x,y) )
  return self.merge(yt, &f) >> y

end

#split_in(n) ⇒ Object

splits a list xs in n peices



12
13
14
# File 'lib/functions/prelude_enumerable/enumerable.rb', line 12

def split_in(n) 
  (split = self.each_slice((self.length+1)/n).to_a).concat [[]] * (n-split.length)
end

#split_in_halfObject



16
17
18
# File 'lib/functions/prelude_enumerable/enumerable.rb', line 16

def split_in_half 
  split_in(2)
end

#unzipObject



7
8
9
# File 'lib/functions/prelude_enumerable/enumerable.rb', line 7

def unzip
  self.transpose
end

#zip_map(*lists, &b) ⇒ Object



3
4
5
# File 'lib/functions/prelude_enumerable/enumerable.rb', line 3

def zip_map *lists, &b
  self.zip(*lists).map(&b)
end