Created
November 2, 2011 02:25
-
-
Save ericmoritz/1332689 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (def collection [1 2 [3 4] [4 5] 6 7 [7 8]]) | |
| ; unchained version | |
| (println | |
| (sort | |
| (distinct | |
| (map #(* % 2) | |
| (flatten collection))))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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