5 ms·
Javascript and Python have similar capabilities, but they're missing the stream fusion optimization mentioned at https://chrisdone.com/posts/stream-composabilit
by sxp 6y ago
Javascript and Python have similar capabilities, but they're missing the stream fusion optimization mentioned at https://chrisdone.com/posts/stream-composability/ https://chrisdone.com/posts/stream-composability/
Javascript:
a = [...Array(20).keys()]
p = x=>!(x%2);
a.slice(3).filter(p).slice(0,3)
Python:
a = range(20)
p = lambda x: not x%2
filter(p, a[3:])[:3]
- pjc50 6y agoYou can also do this nicely in Linq in C#.
- sergeykish 6y agoThe code is not equivalent to Common Lisp (neither is Haskell version), it should remove `count` of elements from the `start` matching a predicate (remove-if-not #'evenp '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) :count 5 :start 3) (1 2 3 4 6 8 10 12 14 15) a = (1..15) r = [] c = [] a.each.with_index do |e, i| if i <= 3 r << e elsif c.length < 5 if e.even? r << e else c << e end else r << e end end r #=> [1, 2, 3, 4, 6, 8, 10, 12, 14, 15] I can see no simple way to compose this a = (1..15) l = a.take(3) c = 0 m = a.drop(3).map.with_index { |e, i| [e, i, e.even?] }.take_while { |e, i, p| c +=1 unless p; c <= 5 } _, last_m_index, _ = m.last m = m.filter { |e, i, p| p }.map { |e, i, p| e } r = a.drop(3 + last_m_index + 1) l + m + r #=> [1, 2, 3, 4, 6, 8, 10, 12, 14, 15]
- anentropic 6y agoin Python 3 both range and filter are lazy but the slices here would spoil it there is https://docs.python.org/3/library/itertools.html#itertools.islice https://docs.python.org/3/library/itertools.html#itertools.i... islice however...