我正试图在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)))
Run Code Online (Sandbox Code Playgroud)
测试:
(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))))
Run Code Online (Sandbox Code Playgroud)
前两个测试工作(2和4),但Fizz和Buzz测试不起作用.我确定我不明白地图索引是如何工作的.
你的if陈述中有一个非常轻微的括号错位.这意味着你没有任何else理由if(因此nil结果)
尝试重写:
(if (clojure.string/blank? v)
(str (+ i 1)
v)))
Run Code Online (Sandbox Code Playgroud)
如:
(if (clojure.string/blank? v)
(str (+ i 1))
v))
Run Code Online (Sandbox Code Playgroud)
ps - 看起来你已经理解了map-indexed fine :)