clojure defn pattern matching
I am really new to clojure, and I want to simulate +
from clojure, I wrote something like this:
(defn sum
([] 0)
([x & xs] (+ x (sum xs))))
(sum 1 2 3 4) ; ERROR
which is not right, as in Haskell, I can write
sum' :: [Int] -> Int
sum' [] = 0
sum' (x:xs) = x + sum' xs
What is the problem with the clojure code ? Thanks!
Correct would be as follows:
(defn sum
([] 0)
([x & xs] (+ x (apply sum xs))))
You were calling the function with one argument, a list, thus hitting the second case over and over until recursion depth exceeded.
链接地址: http://www.djcxy.com/p/82578.html上一篇: 如何解析Clojure定义中的嵌套参数?
下一篇: clojure定义模式匹配