2024年Clojure调查中分享您的想法!

欢迎!请访问关于页面以了解更多关于此如何工作的信息。

0
语法和读者
(defn get-pins [observed]
  (let [num (count observed)
        keypad {\1 [1 2 4] \2 [2 1 5 3] \3 [3 2 6]
                \4 [4 1 5 7] \5 [5 2 6 8 4] \6 [6 3 5 9]
                \7 [7 4 8] \8 [8 5 9 0 7] \9 [9 6 8] \0 [0 8]}
        observed-map (zipmap [:a :b :c :d] (map keypad observed))]
    (case num
      1 (for [a (:a observed-map)]
          (str a))
      2 (for [a (:a observed-map)
              b (:b observed-map)]
         (str a b))
      3 (for [a (:a observed-map)
              b (:b observed-map)
              c (:c observed-map)]
         (str a b c))
      4 (for [a (:a observed-map)
              b (:b observed-map)
              c (:c observed-map)
              d (:d observed-map)]
         (str a b c d))
       "default")))

2 答案

+1

以下将实现您想要的功能

(defn get-pins [observed]
  (let [num (count observed)
        keypad {\1 [1 2 4] \2 [2 1 5 3] \3 [3 2 6]
                \4 [4 1 5 7] \5 [5 2 6 8 4] \6 [6 3 5 9]
                \7 [7 4 8] \8 [8 5 9 0 7] \9 [9 6 8] \0 [0 8]}
        observed-map (zipmap [:a :b :c :d] (map keypad observed))]
    (for [a (:a observed-map) 
          b (or (:b observed-map) [nil]) 
          c (or (:c observed-map) [nil]) 
          d (or (:d observed-map) [nil])] 
      (str a b c d))))

[nil]值将导致一个单一的“迭代”(值nil),在调用str时将产生一个空字符串。

谢谢帮助
0

在这里你提了什么问题?你能详细说明一下吗?

是否可以将case语句改为更灵活的解法,比如单个for语句,并且仍然可以处理各种长度的字符串?
不,`for` 不是为此而设计的。
...