Skip to content

Instantly share code, notes, and snippets.

@ericmoritz
Created November 2, 2011 02:25
Show Gist options
  • Select an option

  • Save ericmoritz/1332689 to your computer and use it in GitHub Desktop.

Select an option

Save ericmoritz/1332689 to your computer and use it in GitHub Desktop.
(def collection [1 2 [3 4] [4 5] 6 7 [7 8]])
(println
(->> collection
flatten
(map #(* % 2)) ; this could use the #(* % 2) lambda shorthand
distinct
sort))
; => (2 4 6 8 10 12 14 16)
from functools import partial
from flatten import flatten
def thread(arg, *sequence):
"""An implementation of Clojure's ->> function"""
for item in sequence:
arg = item(arg)
return arg
collection = [1, 2, [3, 4], [4, 5], 6, 7, [7, 8]]
print thread(collection,
flatten,
partial(map, lambda x: x * 2),
set,
sorted)
def flatten(items):
"""A recursive flatten function."""
if len(items) == 0:
return []
elif len(items) == 1:
first, rest = items[0], []
else:
first, rest = items[0], items[1:]
if type(first) is list:
result = flatten(first)
else:
result = [first]
return result + flatten(rest)
(def collection [1 2 [3 4] [4 5] 6 7 [7 8]])
; unchained version
(println
(sort
(distinct
(map #(* % 2)
(flatten collection)))))
from flatten import flatten
collection = [1, 2, [3, 4], [4, 5], 6, 7, [7, 8]]
print sorted(set(map(lambda x: x * 2, flatten(collection))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment