【心得】
;; 原本找了很久才知道的,跟 ruby 不一樣,不能直覺的 [1, 2, 3][2] QQ
([1 2 3] 2) => 3
;; 但發現如果給的 index 超過範圍會噴 error 而不是預期的 nil
([1 2 3] 3) => IndexOutOfBoundsException: null
;; 這時候就可以用 get
(get [1 2 3] 3) => nil
.indexOf
可以找出給的值對應在 vector 中的 index / (into [] xxx)
的寫法可以做到 convert list or map into vector 效果【今日湯底】
Given a sequence of items and a specific item in that sequence, return the item immediately following the item specified. If the item occurs more than once in a sequence, return the item after the first occurence. This should work for a sequence of any type.
When the item isn't present or nothing follows it, the function should return nil in Clojure and Elixir, Nothing in Haskell, undefined in JavaScript, None in Python.
(next-item (range 1 10000) 7) ;=> 8
(next-item ["Joe" "Bob" "Sally"] "Bob") ;=> "Sally"
(必須通過以下測試)
(ns lazy-next-test
(:require [clojure.test :refer :all]
[lazy-next :refer [next-item]]))
(deftest SampleTests
(is (= (next-item (range 1 25) 12) 13))
(is (= (next-item "testing" \t) \e))
(is (nil? (next-item [:a :b :c] :d)))
(is (nil? (next-item [:a :b :c] :c))))
【我的答案】
(ns lazy-next)
(defn next-item
[xs item]
(let [to-vector (into [] xs)
first-match-index (.indexOf to-vector item)
next-item (if (= -1 first-match-index) nil (get to-vector (inc first-match-index)))]
next-item
)
)
思路:
.indexOf
去找第一個符合值對應的 index【其他人的答案】
wt......好強...function 幾乎都沒看過
(ns lazy-next)
(defn next-item
"Returns the value that comes after item in xs or nil"
([xs item]
(second (drop-while (complement #{item}) xs))))
(ns lazy-next)
(defn next-item [xs item]
(when (not-empty xs)
(if (= item (first xs))
(second xs)
(next-item (rest xs) item))))