本文介绍了在这个简单的例子中展示一流的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请使用这两个重叠的 Clojure 函数为初学者演示代码重用的一流函数(或其他一些函数式编程概念).基本上,使用函数式编程方法简化下面的代码块.
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 和 insertL 是简单的首次出现插入函数.如您所见,它们仅相差一行.
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))))))这是输出.
=> (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))))))更多推荐
在这个简单的例子中展示一流的功能
发布评论