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

编程入门 行业动态 更新时间:2024-10-24 22:28:53
本文介绍了在这个简单的例子中展示一流的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

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

本文发布于:2023-11-06 22:36:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564863.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在这个   例子   简单   功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!