More idiomatic way to calculate GS1 check digit in Clojure

╄→гoц情女王★ 提交于 2019-12-06 02:03:25
(defn check-digit 
  [s] 
  (let [digits        (map #(Integer/parseInt (str %)) s)
        [chk & body]  (reverse digits)
        sum           (apply + (map * body (cycle [3 1])))
        moddiff       (mod (- 10 sum) 10)]
       moddiff))  

This implementation uses two clojure idioms I am conscious of:

  • let to manage local decomposition (and reuse)
  • map with a second collection, being an infinite lazy sequence 'adjacent' to the problem.

Also de-structures list so that would be easy to write the checking predicate as (= moddiff chk).

Threading macros -> ->> are pretty great at chaining function applications

(defn to-digits [s] (map #(Integer/parseInt (str %)) s))

(defn check-digit [string]
 (->> string
   to-digits
   reverse rest
   (map * (cycle [3 1]) )
   (apply +)
   (- 10)
   (#(mod % 10))
   ))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!