clojure循环在map-indexed中返回nil

时间:2013-07-22 12:24:13

标签: clojure

我正在尝试用clojure写一个基于Fizz Buzz的循环。它似乎适用于不是Fizz或Buzz的值,但对于Fizz和Buzz的值,它返回nil。

代码:

(ns fizz-buzz.core
  (:gen-class))

(defn fizz-buzz [value]
  (let [fizz (cycle ["" "" "Fizz"])
        buzz (cycle ["" "" "" "" "Buzz"])
        fb (map str fizz buzz)]
    (nth (map-indexed 
           (fn [i v] 
             (if (clojure.string/blank? v)
               (str (+ i 1)
               v)))
           fb)
         (- value 1)))

试验:

(ns fizz-buzz.core-test
  (:require [clojure.test :refer :all]
            [fizz-buzz.core :refer :all]))

(deftest value-2-will-return-2 
  (testing "2 will return the string 2"
    (is (= "2" (fizz-buzz 2)))))

(deftest value-4-will-return-4 
  (testing "4 will return the string 4"
    (is (= "4" (fizz-buzz 4)))))

(deftest value-3-will-return-fizz
  (testing "3 will return the string Fizz"
    (is (= "Fizz" (fizz-buzz 3)))))

(deftest value-5-will-return-buzz
  (testing "5 will return the string Buzz"
    (is (= "Buzz" (fizz-buzz 5))))

前两个测试工作(2和4),但Fizz和Buzz测试不起作用。我确信我不明白地图索引是如何工作的。

1 个答案:

答案 0 :(得分:5)

您的if声明中有一个非常轻微的括号错位。 这意味着您的else没有if个案(因此nil结果)

尝试重写:

(if (clojure.string/blank? v)
           (str (+ i 1)
           v)))

如:

(if (clojure.string/blank? v)
           (str (+ i 1))
           v))

ps - 看起来你已经理解了map-indexed fine:)