gpt4 book ai didi

functional-programming - 在这个简单的例子中演示一流的功能

转载 作者:行者123 更新时间:2023-12-01 01:57:45 24 4
gpt4 key购买 nike

<分区>

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com