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 '()]
tail (rest remain)]

; 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 Replies to “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=&gt; (defn example [a b]
(defn sum [x y]
(+ x y))
(sum a b))
#'user/example
user=&gt; (example 1 2)
3
user=&gt; (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

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.