99 Clojure Problems (5-6)

Clojure’s been strange so far. After tinkering in F# for the last couple months, it seems like functional programming should be easier by now.

Reverse and palindrome were easy enough, though.

; P05 (*) Reverse a list.
; clojure already has a (reverse l)
(defn s99_reverse [l]
  (loop [remain l
         curr '()] 
    (let [head (first remain)
         tail (rest remain)]
      (if (nil? head) curr (recur tail (cons head curr)))))

; P06 (*) Find out whether a list is a palindrome.
(defn isPalindrome [l] (= l (reverse l)))

I’m slowly getting my brain around the lisp like syntax, but it appears that some of the idioms are different. I’ll discuss this more when I get to the next set.

4 thoughts on “99 Clojure Problems (5-6)”

  1. The way you are defining inner functions is probably doing something you aren’t expecting. Currently that inner method would be available at the outer scope.

    Here is an example at the repl:

    user=> (defn example [a b]
                 (defn sum [x y]
                    (+ x y))
                 (sum a b))
    #'user/example
    user=> (example 1 2)
    3
    user=> (sum 1 2)
    3

    You’ll probably want to look up the letfn and loop constructs.

  2. Thanks! You definitely helped me crack the “mystery” of the loop construct and the let construct for me. I think I’m back on the right track.

  3. Hello
    I wanted to add your blog into Planet Clojure, but feed content isn’t correct – I couldn’t subscribe to entries in Google Reader, and Firefox gives me error. Please check settings, and write to me, so I’ll add your blog

  4. You will eventually learn about conj (if you haven’t already) which puts something onto the beginning of a list. If you take that with the function reduce, you can conj everything from a list onto the beginning of an empty list.

    (defn reverse [coll] (reduce conj () coll))

    you’ll also find out that this is the way clojure’s reverse is written. that is the best source for understanding clojure. much of clojure is written in clojure, so reading through the source is a fantastic learning tool.

    in your repl try this:
    (use ‘clojure.contrib.repl-utils)
    (source reverse)
    (source count)
    (source …….) ;;try anything you’re unsure of

    also use doc which is another great tool if you aren’t using it already.

    (doc doc)

Leave a Reply

Your email address will not be published. Required fields are marked *