4clojure第58个问题:组合函数

本文介绍了一种在Clojure中实现函数组合的方法,通过两个不同的函数组合实现展示了如何灵活地组合多个函数,并提供了具体的示例代码来说明其用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(ns for-clojure.problem58)
(defn fn-comp-1
  "创建一个函数的组合函数,此函数接受任何个数的函数,从右到左执行函数"
  [& fns]
  (fn [& init-paramters]
    (let [fns (reverse fns)
          result (apply (first fns) init-paramters)]
      (loop [fns (rest fns) result result]
        (if (empty? fns) 
          result
          (recur (rest fns) ((first fns) result)))))))

((fn-comp-1 rest reverse) [1 2 3 4]) ;= [3 2 1]
((fn-comp-1 (partial + 3) second) [1 2 3 4]) ;= 5
((fn-comp-1 zero? #(mod % 8) +) 3 5 7 9) ;= true
((fn-comp-1 #(.toUpperCase %) #(apply str %) take) 5 "hello world") ;= "HELLO"

(defn fn-comp-2
  "非尾递归版本"
  [& fns]
  (fn [& xs]
    (let [fns (reverse fns)
          result (apply (first fns) xs)]
      (reduce #(%2 %1) result (rest fns)))))

((fn-comp-2 rest reverse) [1 2 3 4]) ;= [3 2 1]
((fn-comp-2 (partial + 3) second) [1 2 3 4]) ;= 5
((fn-comp-2 zero? #(mod % 8) +) 3 5 7 9) ;= true
((fn-comp-2 #(.toUpperCase %) #(apply str %) take) 5 "hello world")  ;= "HELLO"

在创建组合函数的过程中,主要是第一个函数比较特别,因为它的参数不确定,因此必须在reduce之前把它处理掉。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值