threading through a vector of functions [duplicate] - clojure

This question already has answers here:
Piping data through arbitrary functions in Clojure
(3 answers)
Closed 8 years ago.
I have a vector of functions (def my-func [a b c d]). Each function takes the output of the last function as the input. I want to thread an input through them, how do I do that?
How do I get to the following form (-> in a b c d)?
Thanks,
Murtaza

You can use comp but be aware it executes the functions right to left
((comp d c b a) 10)
or
((apply comp my-fns) 10)
will pass 10 to the first function, the result to the next function and so on.

I think you can use the reduce function:
(def fns [inc inc inc])
(reduce (fn [v f] (f v)) 10 fns)

Related

In Clojure, what does `&` mean in function/macro signature?

I saw the usage of & in Clojure function signature like this (http://clojure.github.io/core.async/#clojure.core.async/thread):
(thread & body)
And this:
(doseq seq-exprs & body)
Does that means the function/macro can accept a list as variable? I also find * is often used to mean multiple parameters can be accepted, like this:
(do exprs*)
Does anyone have ideas about the difference between & and * in function/macro signature? Is there any documentation to explain this syntax?
It means that there can be multiple parameters after the ampersand, and they will be seen as a seq by the function. Example:
(defn g [a & b]
(println a b))
Then if you call:
(g 1 2 3 4)
it will print out 1 (2 3 4) (a is 1, b is a sequence containing 2, 3 and 4).
In clojure binding forms (let, fn, loop, and their progeny), you can bind the rest of a binding vector to a sequence with a trailing &. For instance,
(let [[a b & xs] (range 5)] xs) ;(2 3 4)
Uses of * and other uses of & are conventions for documenting the structure of argument lists.

Clojure Higher-order functions take function arguments, but what is the syntax?

I am doing the closure tutorial at http://clojurescriptkoans.com and I am stuck here: http://clojurescriptkoans.com/#functions/9
It looks like this
Higher-order functions take function arguments
(= 25 ( _ (fn [n] (* n n))))
I am supposed to fill in something at the underscore to make the expression true. I have no clue what to do.
The syntax simply consists of binding the function, and then calling it.
Since this is an exercise, I will show a similar situation rather than showing the exercise's solution:
user> ((fn [f] (f "abc")) (fn [s] (str s s s)))
"abcabcabc"
here I bind the argument of the first function to f, and call f with the argument "abc".
or you can use the short-hand notation:
#(%1 5)
Higher order functions takes functions as arguments.
Defining two functions
user=> (defn multiply [n] (* n n))
#'user/multiply
user=> (defn add [n] (+ n n))
#'user/add
Defining higher order function
user=> (defn highorderfn [fn number] (fn number))
#'user/highorderfn
Calling the higher order function
user=> (highorderfn multiply 5)
25
user=> (highorderfn add 5)
10

Syntax issue in Clojure Koan - anonymous function has extra ()

06_function.clj contains this question, I can't figure out why there is an extra pair of () in position 1 and 2, since position 3 already has brackets wrapped up.
"One function can beget another"
(= 9 (
( <---- 1
(fn [] (fn [a b] (+ a b))) <----3
) <-----2
4 5))
(fn [a b] (+ a b))
is a function that takes 2 arguments and returns their sum, let's substitute if with name fun1
(fn [] fun1)
is a function that takes nothing and returns function object fun1. Let's call this new function fun2
(
fun2
)
here we call fun2, which, as we previously discussed, returns function fun1
(
fun1
4 5)
here we call fun1 (returned from (fun2)) with 2 arguments - 4 and 5. This gives us 9
(= 9
9)
and finally we check equality of 2 numbers. They are actually equal.
The main thing you should understand here is that functions in Clojure are also first-class citizens. You may produce them (like fun1), pass them to other functions and return from them (like we returned fun1 from fun2). So each layer of ( and ) is just another call to a function (possibly returned from some other function).
It's there to evaluate the function created by outer fn.
So, in turn:
(fn [a b] (+ a b)
creates the inner function that sums it's arguments
(fn [] (fn [a b] (+ a b))
creates the outer function with taking zero arguments and returning a function that sums it's arguments.
(
(fn [] (fn [a b] (+ a b)))
)
forces evaluation of the outer function (and returns it's result - a function that sums two values).
Remember that when you see parentheses in lisps the first thing that should pop in your mind is that it's an application of the function/form/macro to it's arguments.

How to apply values to multiple functions in Clojure?

Basically, I need to do something like map, but instead of applying a function to all elements in a collection, I need to apply the same (set of) value(s) to a collection of functions (does this operation have a name?). This might seem like a simple question, but I haven't found an idiomatic way to do it in Clojure. For the special case where I need to apply only one value to each function, for example, I have used
(for [f funs] (f value))
where value is, of course, the value I need each function to take as an argument, and funs is the collection of functions which need to be called with value as the argument.
My question is, then, is there a function in Clojure that does this, but is also generalised for arbitrary numbers of arguments? Or is the above indeed idiomatic Clojure?
You're looking for juxt
juxt
Takes a set of functions and returns a fn that is the juxtaposition
of those fns. The returned fn takes a variable number of args, and
returns a vector containing the result of applying each fn to the
args (left-to-right).
((juxt a b c) x) => [(a x) (b x) (c x)]
From a section of CLOJURE for the BRAVE and TRUE
Another fun thing you can do with map is pass it a collection of
functions. You could use this if you wanted to perform a set of
calculations on different collections of numbers, like so:
(def sum #(reduce + %))
(def avg #(/ (sum %) (count %)))
(defn stats
[numbers]
(map #(% numbers) [sum count avg]))
(stats [3 4 10])
; => (17 3 17/3)
(stats [80 1 44 13 6])
; => (144 5 144/5)

Higher-order functions in Clojure

Clojure is awesome, we all know this, but that's not the point. I'm wondering what the idiomatic way of creating and managing higher-order functions in a Haskell-like way is. In Clojure I can do the following:
(defn sum [a b] (+ a b))
But (sum 1) doesn't return a function: it causes an error. Of course, you can do something like this:
(defn sum
([a] (partial + a))
([a b] (+ a b)))
In this case:
user=> (sum 1)
#<core$partial$fn__3678 clojure.core$partial$fn__3678#1acaf0ed>
user=> ((sum 1) 2)
3
But it doesn't seem like the right way to proceed. Any ideas?
I'm not talking about implementing the sum function, I'm talking at a higher level of abstraction. Are there any idiomatic patterns to follow? Some macro? Is the best way defining a macro or are there alternative solutions?
Someone has already implememented this on the Clojure group. You can specify how many args a function has, and it will curry itself for you until it gets that many.
The reason this doesn't happen by default in Clojure is that we prefer variadic functions to auto-curried functions, I suppose.
I've played a bit with the functions suggested by amalloy. I don't like the explicit specification of the number of argument to curry on. So I've created my custom macro. This is the old way to specific an high order function:
(defn-decorated old-sum
[(curry* 3)]
[a b c]
(+ a b c))
This is my new macro:
(defmacro defn-ho
[fn-name & defn-stuff]
(let [number-of-args (count (first defn-stuff))]
`(defn-decorated ~fn-name [(curry* ~number-of-args)] ~#defn-stuff)))
And this is the new implicit way:
(defn-ho new-sum [a b c] (+ a b c))
As you can see there is no trace of (curry) and other stuff, just define your currified function as before.
Guys, what do you think? Ideas? Suggestions?
Bye!
Alfedo
Edit: I've modified the macro according the amalloy issue about docstring. This is the updated version:
(defmacro defhigh
"Like the original defn-decorated, but the number of argument to curry on
is implicit."
[fn-name & defn-stuff]
(let [[fst snd] (take 2 defn-stuff)
num-of-args (if (string? fst) (count snd) (count fst))]
`(defn-decorated ~fn-name [(curry* ~num-of-args)] ~#defn-stuff)))
I don't like the if statement inside the second binding. Any ideas about making it more succint?
This will allow you to do what you want:
(defn curry
([f len] (curry f len []))
([f len applied]
(fn [& more]
(let [args (concat applied (if (= 0 (count more)) [nil] more))]
(if (< (count args) len)
(curry f len args)
(apply f args))))))
Here's how to use it:
(def add (curry + 2)) ; read: curry plus to 2 positions
((add 10) 1) ; => 11
The conditional with the [nil] is meant to ensure that every application ensures some forward progress to the curried state. There's a long explanation behind it but I have found it useful. If you don't like this bit, you could set args as:
[args (concat applied more)]
Unlike JavaScript we have no way of knowing the arity of the passed function and so you must specify the length you expect. This makes a lot of sense in Clojure[Script] where a function may have multiple arities.