How to build a function from a list of functions and values?

I am trying to build a function from the results of one already evaluated function and a list of other functions. If I partially build it, it works fine, but every time I try to build the whole thing, it fails.

(defn play [] 
    (let [eval1 (eval '(+ 1 1))]
        (eval `(->> ~eval1 (+ 5) (- 2) (* 7)))
    )
)

This fails:

(defn play []
    (let [eval1 (eval '(+ 1 1))
          eval2 '((+ 5) (- 2) (* 7))]
        (eval (cons (cons eval1 eval2) ->>))
     )
)

I tried many other ways to put this together, and I think it comes down to the fact that I do not quite understand this aspect of clojure. What is the best way to solve this problem? Thank!

+4
source share
3 answers

eval. , , - ( Clojure ). , " ".

1 - eval

. Webb answer . - , , Clojure, .

2 - eval

, eval. (eval '(+ 1 1)) (+ 1 1). , , #(+ 5 %) .. (partial + 5) .. .

->> - . , , S-. S- - S- cons, .

, , . , , reduce:

(defn play []
    (let [eval1 (+ 1 1)
          eval2 (list #(+ 5 %) #(- 2 %) #(* 7 %))]
        (reduce #(%2 %) eval1 eval2)))

, , core.clj:

(defn freduce
   "Given an initial input and a collection of functions (f1,..,fn),
   This is logically equivalent to ((comp fn ... f1) input)."
   [in fs]
   (reduce #(%2 %) in fs))

, , , fn:

(defn play []
    (let [in (+ 1 1)
          fs (list #(+ 5 %) #(- 2 %) #(* 7 %))]
        (fn [] (freduce in fs))))

user=> ((play))
-35
+4

play: (1) ->>, Clojure "tak [ing] ", ; (2) cons .

Try

(defn play []
  (let [eval1 (eval '(+ 1 1))
        eval2 '((+ 5) (- 2) (* 7))]
    (eval (cons '->> (cons eval1 eval2)))))

, , - , , list* cons.

+1

(+ 1 1) , '((+ 5) (- 2) (* 7)) .

,

(def fns (list (partial + 5) (fn [x] (- 2 x)) #(* 7 %)))

" "

(def master-fn (->> fns reverse (apply comp)))

" []":

(master-fn (+ 1 1))
;; => -35
0

Source: https://habr.com/ru/post/1534278/


All Articles