在这个简单的例子中展示出一流的功能

时间:2011-05-17 15:12:58

标签: functional-programming clojure abstraction code-reuse

请使用这两个重叠的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)

1 个答案:

答案 0 :(得分:2)

以下是使用第一类函数重构此内容的示例:

(defn insert [newkey oldkey lat f]
  (if (empty? lat)
    '()
    (if (= (first lat) oldkey)
      (f oldkey newkey lat)
      (cons (first lat) (insert newkey oldkey (rest lat) f)))))

(defn insertL [newkey oldkey lat]
  (insert newkey oldkey lat 
    (fn [oldkey newkey lat] (cons newkey lat))))

(defn insertR [newkey oldkey lat]
  (insert newkey oldkey lat 
    (fn [oldkey newkey lat] (cons oldkey (cons newkey (rest lat))))))
相关问题