【发布时间】:2011-08-27 08:12:18
【问题描述】:
请为使用这两个重叠 Clojure 函数的初学者演示代码重用的一流函数(或其他一些函数式编程概念)。基本上,使用函数式编程方法简化下面的代码块。
作为比较,您将如何使用您选择的其他函数式语言进行比较?
insertR 和 insertL 是简单的首次出现插入函数。如您所见,它们仅相差一行。
;test case
(def newkey :cake)
(def oldkey :and)
(def lat '(:bacon :lettuce :and :tomato :and :jelly)) ; list of keywords
(defn insertR [newkey oldkey lat]
(if (empty? lat)
'()
(if (= (first lat) oldkey)
(cons oldkey (cons newkey (rest lat))) ;;; diff line
(cons (first lat) (insertR newkey oldkey (rest lat))))))
(defn insertL [newkey oldkey lat]
(if (empty? lat)
'()
(if (= (first lat) oldkey)
(cons newkey lat) ;;; diff line
(cons (first lat) (insertL newkey oldkey (rest lat))))))
这是输出。
=> (insertR newkey oldkey lat)
(:bacon :lettuce :and :cake :tomato :and :jelly)
=> (insertL newkey oldkey lat)
(:bacon :lettuce :cake :and :tomato :and :jelly)
【问题讨论】:
-
没有。我正在自己学习函数式编程,这个问题刚刚出现在我身上。我可以通过模板模式在 OO 中做到这一点,但无法弄清楚如何在 FP 中做到这一点。
标签: functional-programming clojure abstraction code-reuse