Skip to content

Instantly share code, notes, and snippets.

@georgepsarakis
Last active August 29, 2015 14:20
Show Gist options
  • Save georgepsarakis/7485247b531fdd485e4c to your computer and use it in GitHub Desktop.
Save georgepsarakis/7485247b531fdd485e4c to your computer and use it in GitHub Desktop.
Python small recipes translated to their Clojure equivalents
;; Regular Expressions
;; import re; re.search(r'ab.*', 'cabbage').group(0) # -> 'abbage'
(re-find #"ab.*" "cabbage") ; "abbage"
;; re.match(r'ab.*', 'cabbage') # -> None
(re-matches #"ab.*" "cabbage") ; nil
;; re.match(r'ab.*', 'abracatabra').group(0) # -> 'abracatabra'
(re-matches #"ab.*" "abracatabra") ; "abracatabra"
;; Sequences & Map/Filter
;; map(str.upper, ['this', 'is', 'a', 'test']) # -> ['THIS', 'IS', 'A', 'TEST']
(map clojure.string/upper-case ["this" "is" "a" "test"])
;; filter(lambda x: x > 5, range(10)) # -> [6, 7, 8, 9]
(filter (fn [x] (> x 5)) (range 10))
;; import itertools; itertools.ifilterfalse(lambda x: x > 5, range(10)) # -> [0, 1, 2, 3, 4, 5]
(remove (
fn [x]
(> x 5)
)
(range 10)
)
;; import itertools; list(itertools.imap(lambda x: random.randint(*x), itertools.repeat((0, 999), 10)))
;; # -> [17, 33, 714, 932, 589, 746, 956, 398, 780, 348]
(take 10 (repeatedly #(rand-int 1000))) ; (41 194 433 441 603 821 802 67 943 400)
;; map(int, ["1", "2", "3"]) # -> [1, 2, 3]
;; read-string will do the conversion to the appropriate primitive - either integer or float
(map int (map read-string ["1" "2" "3"]))
;; Dictionaries (hash map)
;; h = {"a": 1, "b": 2}; map(lambda x: "{0}-{1}".format(*x), h.items()) # -> ['a-1', 'b-2']
(def h {"a" 1, "b" 2})
(map (fn [x] (apply format "%s-%d" x)) (seq h))
;; Sets
;; set([1, 2, 3]).issubset(set([ 1 1 2 3 2 4 8 10 ]))
(clojure.set/subset? #{1 2 3} (set [ 1 1 2 3 2 4 8 10 ]))
;; set([1, 2, 3, 9, ]).union(set([1, 5, 7, 2]))
(clojure.set/union #{1 2 3 9} #{1 5 7 2})
;; set([1, 2, 3, 9, ]).intersection(set([1, 5, 7, 2]))
(clojure.set/intersection #{1 2 3 9} #{1 5 7 2})
;; set([1, 2, 3, 9, ]) - set([1, 5, 7, 2]) # -> set([9, 3])
(clojure.set/difference #{1 2 3 9} #{1 5 7 2}) ; #{3 9}
;; set([1, 5, 7, 2]) - set([1, 2, 3, 9, ]) # -> set([5, 7])
(clojure.set/difference #{1 5 7 2} #{1 2 3 9}) ; #{7 5}
;; 10 in set([1, 2, 3]) # -> False
(contains? #{1 2 3} 10) ; false
;; Strings
;; "a_b_c".split("_")
(clojure.string/split "a_b_c" #"_")
;; "_".join(["a", "b", "c"])
(clojure.string/join "_" [ "a" "b" "c" ])
;; isinstance(1, (long, int))
(integer? 1)
;; import random; random.randint(0, 999)
(rand-int 1000)
;; import functools
;; def f(x, y): return x * y
;; g = functools.partial(f, 2)
;; g(3) # -> 6
(defn f [x y] (* x y))
(def g (partial f 2))
(g 3) ; 6
;; reduce(lambda x, y: x * y, range(1, 10))
(reduce * (range 1 10)) ; 362880
;; range(10, 20)[9]
(nth (range 10 20) 9)
;; [1, 2, 3].index(2)
(.indexOf '(1 2 3) 2)
;; list -> vector
(vec '(1 2 3))
;; vector -> list
(into '() [1 2 3])
;; [2 * r for r in range(10)]
(for [
r (range 10)
:let [ p (* 2 r) ]
]
p)
;; import itertools
;; [2 * x for x in itertools.ifilter(lambda x: x % 2 == 0, range(10))]
;; # -> [0, 4, 8, 12, 16]
(for [
r (range 10)
:let [ p (* 2 r) ]
:when (even? r)
]
p)
;; def f(x):
;; if x > 2:
;; if x > 10:
;; r = "{} is greater than 10!".format(x)
;; else:
;; r = "{} is lower-equal than 10!".format(x)
;; else:
;; r = "x <= 2 -> {}".format(x)
;; print r
;; return r
(defn f [x]
(
prn (
if (> x 2)
(
if (> x 10)
(format "%d is greater than 10!" x)
(format "%d is lower-equal than 10!" x)
)
(
format "x <= 2 -> %d" x
)
)
)
)
;; dict([('key-{}'.format(index), 'val-{}'.format(n)) for index, n in enumerate(range(4))])
;; # -> {'key-3': 'val-3', 'key-2': 'val-2', 'key-1': 'val-1', 'key-0': 'val-0'}
(apply hash-map (
flatten
(
keep-indexed
#(
identity [
(clojure.string/join "-" ["key" (str %1)])
(clojure.string/join "-" ["val" (str %2)])
]
)
(range 4)
)
)
)
;; {"a": 1, "b": 2}.keys()
(keys {"a" 1, "b" 2}) ; ("a" "b")
;; list(reversed(range(10, 15)))
(rseq (vec (range 10 15))) ; (14 13 12 11 10)
;; import re; re.sub(r"p[a-z]*", "B", "this is an example for the Clojure replace function")
(clojure.string/replace "this is an example for the Clojure replace function" #"p[a-z]*" "B")
;; filter(lambda x: x > 18, sorted([10, 98, 20, 33, 18]))
(subseq (sorted-set 10 98 20 33 18) > 18) ; (20 33 98)
;; import itertools
;; list(itertools.imap(next, itertools.repeat((n for n in itertools.count(5)), 10)))
(take 10 (iterate inc 5))
(repeat 3 (take 4 (iterate inc 3))) ; ((3 4 5 6) (3 4 5 6) (3 4 5 6))
;; import random
;; random.choice(range(1000))
(rand-nth (range 1000))
;; def partition_all(L, p):
;; return [L[p * n:p * (n + 1)] for n in range(int(1 + len(L) / p))]
(partition-all 2 (range 8)) ; ((0 1) (2 3) (4 5) (6 7))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment