开发者

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

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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.

=>开发者_StackOverflow社区 (insertR newkey oldkey lat)
(:bacon :lettuce :and :cake :tomato :and :jelly)
=> (insertL newkey oldkey lat)
(:bacon :lettuce :cake :and :tomato :and :jelly)


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜