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

你在这里问的是什么问题?你能详述一下吗?

能否将情况语句改为一种不太硬编码的解决方案,例如单条for语句,并仍能用这种方式处理不同长度的字符串。
不行,`for` 不是为此而生的。
...