Skip to content

Instantly share code, notes, and snippets.

@zaneli
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaneli/10492423 to your computer and use it in GitHub Desktop.
Save zaneli/10492423 to your computer and use it in GitHub Desktop.
「ClojureでNinety-Nine Lisp Problems(P06~10)」ブログ用
(defn my-palindrome?
"Find out whether a list is a palindrome."
[word]
(let [middle (/ (count word) 2), word1 (take middle word), word2 (reverse (drop middle word))]
(every? #(= (first %) (second %)) (map list word1 word2))
)
)
(defn my-palindrome?
"Find out whether a list is a palindrome."
[word]
(let [words (split-at (/ (count word) 2) word)]
(every? #(= (first %) (second %)) (map list (first words) (reverse (second words))))
)
)
(defn my-palindrome?
"Find out whether a list is a palindrome."
[word]
(let [words (split-at (/ (count word) 2) word)]
(every? #(= (key %) (val %)) (zipmap (first words) (reverse (second words))))
)
)
(defn my-flatten
"Flatten a nested list structure."
[[x & xs :as lst]]
(if (empty? lst)
nil
(if (list? x)
(concat (my-flatten x) (my-flatten xs))
(cons x (my-flatten xs))
)
)
)
(defn my-compress
"Eliminate consecutive duplicates of list elements."
[xs]
(if (empty? xs)
nil
(cons (first xs) ((fn f [[x1 & xs] ys]
(let [x2 (first xs)]
(cond (empty? xs) ys
(= x1 x2) (f xs ys)
:else (cons x2 (f xs ys))
)
)
) xs '()))
)
)
(defn my-compress
"Eliminate consecutive duplicates of list elements."
[xs]
(if (empty? xs)
nil
(reverse ((fn [[x & xs] ys]
(if (nil? x)
ys
(recur ((fn [x] (drop-while #(= % x) xs)) x) (cons x ys))
)
) xs '()))
)
)
(defn my-compress
"Eliminate consecutive duplicates of list elements."
[xs]
(if (empty? xs)
nil
(reverse (loop [xs xs, ys '()]
(if (empty? xs)
ys
(let [x (first xs)]
(recur ((fn [x] (drop-while #(= % x) xs)) x) (cons x ys))
)
)
))
)
)
(defn my-pack
"Pack consecutive duplicates of list elements into sublists."
[xs]
(reverse (loop [xs xs, ys '()]
(if (empty? xs)
ys
(let [x (first xs), y (take-while #(= x %) xs)]
(recur (drop (count y) xs) (cons y ys))
)
)
))
)
(defn my-pack
"Pack consecutive duplicates of list elements into sublists."
[xs]
(reverse (loop [xs xs, ys '()]
(if (empty? xs)
ys
(let [x (first xs), y (split-with #(= x %) xs)]
(recur (second y) (cons (first y) ys))
)
)
))
)
(defn my-pack
"Pack consecutive duplicates of list elements into sublists."
[xs]
(partition-by identity xs)
)
(defn my-encode
"Run-length encoding of a list."
[xs]
(reverse (loop [[x & _ :as xs] xs, ys '()]
(if (nil? x)
ys
(let [[z zs] (split-with #(= x %) xs)]
(recur zs (cons (list (count z) (first z)) ys))
)
)
))
)
(defn my-encode
"Run-length encoding of a list."
[xs]
(map #(list (count %) (first %)) (partition-by identity xs))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment