在这个简单的例子中展示一流的功能
请使用这两个重叠的 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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(1)
下面是使用一等函数重构它的示例:
Here's an example of refactoring this using first-class functions: