Mik*_*din 1 coding-style clojure
我大约一周参加Clojure和函数式编程 - 我的所有背景都是在OOP中.我想利用Clojure滔滔不绝的易读性和内在逻辑,但是现在我不知道我是否成功地做到了这一点并且没有完全包围我的想法,或者我是否真的在滥用语言以一种糟糕的方式.
例如:
(ns waterfall-quiz.response-parser
(:require [clojure.java.io :as io]))
(defn process-input
[input]
(finalize-input
(normalize-height
(map-input
(numberize-vector
(vectorize-input
(clean-input input)))))))
(defn clean-input
"Removes extraneous whitespace."
[input]
(clojure.string/replace input #"\s+" " "))
(defn vectorize-input
"Turns input into a vector."
[input]
(clojure.string/split input #"\s"))
(...)
Run Code Online (Sandbox Code Playgroud)
我非常怀疑process-input函数,它调用所有其他函数来格式化一些输入.它是引用透明的,但看起来很脆弱 - 是否有更智能的方法将所有功能链接在一起?
另一个例子:
(defn map-builder
"Transforms the vector of waterfalls into a map of waterfalls."
[vectorized-db]
(assoc waterfall-db
(keyword (str 'waterfall (first (re-seq #"[0-9]+" (str (first vectorized-db))))))
(subs (str (first vectorized-db)) (+ 2 (.indexOf (str (first vectorized-db)) ":")))))
Run Code Online (Sandbox Code Playgroud)
在编写该函数时,我不断地在括号中忘记了我的位置 - 它应该被分解为更小的函数吗?
最能改进代码的两个惯用工具Clojure是let和->宏.
let 允许您逐步构建本地绑定
-> 以更易读和更易于编辑的形式将一系列函数调用链接在一起
(defn process-input
[input]
(-> input
clean-input
vectorize-input
numberize-vector
map-input
normalize-height
finalize-input))
(defn map-builder
"Transforms the vector of waterfalls into a map of waterfalls."
[waterfall-db vectorized-db]
(let [key-str (str (first vectorized-db))
key (->> key-str
(re-seq #"[0-9]+")
first
(str 'waterfall)
keyword)
val (subs key-str (+ 2 (.indexOf key-str ":")))]
(assoc waterfall-db key val)))
Run Code Online (Sandbox Code Playgroud)
我也参加了制作的自由waterfall-db对Arg的映射,生成器,它可以在功能代码(也许的帮助下更容易使用swap!,reduce或update-in).
| 归档时间: |
|
| 查看次数: |
399 次 |
| 最近记录: |