falzm/aphyr_clojure_seq.clj
Last active
Some Clojure exercise
| ;;; Solutions to http://aphyr.com/posts/304-clojure-from-the-ground-up-sequences problems | |
| ; 1. Write a function to find out if a string is a palindrome–that is, if it looks the same forwards and backwards. | |
| (defn palindrome? | |
| "Find out if the string is a palindrome" | |
| [s] | |
| (= | |
| s | |
| (apply str (reverse s)))) | |
| ; user=> (palindrome? "blah") | |
| ; false | |
| ; user=> (palindrome? "kayak") | |
| ; true | |
| ; user=> (palindrome? "bob") | |
| ; true | |
| ; user=> (palindrome? "bobby") | |
| ; false | |
| ; 2. Find the number of ‘c’s in “abracadabra”. | |
| ; user=> (count (filter (fn [c] (= c \c)) (seq "abracadabra"))) | |
| ; 1 | |
| ; 3. Write your own version of `filter`. | |
| ; (thanks to baloo (github.com/baloo) for the original idea) | |
| (defn my-filter [f coll] | |
| (into [] | |
| (apply concat | |
| (map | |
| (fn [x] | |
| (if (f x) [x] [])) | |
| coll)))) | |
| ; user=> (my-filter even? [1 2 3 4]) | |
| ; [2 4] | |
| ; user=> (my-filter pos? (take 10 (iterate inc -5))) | |
| ; [1 2 3 4] | |
| ; 4. Find the first 100 prime numbers: 2, 3, 5, 7, 11, 13, 17, … | |
| ; user=> (take 100 (filter (fn [x] (> (mod x 2) 0)) (iterate inc 0))) | |
| ; (1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 101 103 105 107 109 111 113 115 117 119 121 123 125 127 129 131 133 135 137 139 141 143 145 147 149 151 153 155 157 159 161 163 165 167 169 171 173 175 177 179 181 183 185 187 189 191 193 195 197 199) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment