【问题标题】:Demonstrate first-class functions in this simple example [closed]在这个简单的例子中演示一流的功能[关闭]
【发布时间】:2011-08-27 08:12:18
【问题描述】:

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

【问题讨论】:

  • 没有。我正在自己学习函数式编程,这个问题刚刚出现在我身上。我可以通过模板模式在 OO 中做到这一点,但无法弄清楚如何在 FP 中做到这一点。

标签: functional-programming clojure abstraction code-reuse


【解决方案1】:

这是一个使用一等函数重构它的示例:

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

【讨论】:

  • 是的,这适用于这个特定的例子。我正在寻找一些函数式编程的插图来展示一种更强大的方法。特别是,我怎样才能在其中使用一流的功能?
  • mmhh 那不是真正的clojury。将 (if (empty?lat) '() ....) 替换为 (when (seq lat) ...)。在 clojure 中,我们替换 nil 而不是空列表。
  • @nickik - 这个问题是关于向初学者展示如何使用一流的函数,而不是关于遵守 Clojure 成语...
  • @rshallit 当然,但我认为对于初学者来说,学习正确的(clojure)方法很重要。这绝不是批评,只是一点点补充。
猜你喜欢
  • 2021-12-28
  • 1970-01-01
  • 2021-07-19
  • 1970-01-01
  • 2011-06-21
  • 1970-01-01
  • 2013-07-04
  • 2020-08-01
  • 1970-01-01
相关资源
最近更新 更多