Demonstrate first-class functions in this simple example [closed]

这一生的挚爱 提交于 2019-12-10 17:45:55

问题


Please demonstrate first-class functions (or some other functional programming concept) for code reuse for a beginner using these two overlapping Clojure functions. Basically, simplify the code block below using functional programming methods.

As a comparison, how would you do it in your other functional language of choice?

insertR and insertL are simple first-occurrence insertion functions. As you can see, they only differ by one line.

;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))))))

Here are the outputs.

=> (insertR newkey oldkey lat)
(:bacon :lettuce :and :cake :tomato :and :jelly)
=> (insertL newkey oldkey lat)
(:bacon :lettuce :cake :and :tomato :and :jelly)

回答1:


Here's an example of refactoring this using first-class functions:

(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))))))


来源:https://stackoverflow.com/questions/6033006/demonstrate-first-class-functions-in-this-simple-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!