Last active
February 2, 2020 12:34
-
-
Save gabehollombe/7854417 to your computer and use it in GitHub Desktop.
Clojure from the Ground Up - Sequences - Exercises
My answers to the exercises from: http://aphyr.com/posts/304-clojure-from-the-ground-up-sequences
This file contains 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
; Sequences | |
;-------------------------------------------------- | |
; Write a function to find out if a string is a palindrome–that is, if it looks the same forwards and backwards. | |
(defn revStr | |
"Reverses s and returns as a string" | |
[s] | |
(apply str (reverse s))) | |
(defn palindrome? | |
[s] | |
(= s (revStr s))) | |
; Find the number of ‘c’s in “abracadabra”. | |
(count (filter #(= % \c) "abracadabra")) | |
; Or | |
((frequencies "abracadabra") \c) | |
; Write your own version of filter. | |
(defn my-filter | |
[pred coll] | |
(reduce (fn [result val] | |
(if (pred val) | |
(conj result val) | |
result)) | |
[] | |
coll)) | |
; Find the first 100 prime numbers | |
(defn divisible? [x y] (= (rem x y) 0)) | |
(defn prime? [n] | |
(not-any? #(divisible? n %) (range 2 n))) | |
(take 100 (filter prime? (iterate inc 2) )) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this. As a beginner to the Clojure language, I did not know about the 'not-any?' function. That really makes the prime number problem easier.