# Tag Info

## Hot answers tagged pure-function

21

As far as I know there is no way to do this with the named parameter form of Function but you can use destructuring methods with SlotSequence (##): f = {##} /. {u_: 1, v_: 0} :> body[u, v] &; f[] f[7] f[7, 8] body[1, 0] body[7, 0] body[7, 8] It is possible to give your pure function Attributes using an undocumented form. For Hold attributes ...

17

You can always string several anonymous functions together, but you'll also have to pay attention to operator precedence. In this case, you had to enclose the anonymous function in parentheses. Replace the corresponding line in your second example with the following and it works. ChartLabels -> (DateString[#, {"ShortDay", "/", "ShortMonth"}] & @@@ ...

15

You can always use Function to create anonymous functions: Function[{a},a^2] is equivalent to #^2& and can be used as such, but it is unambiguous. It can be used as: Function[{a},a^2][2] (* ==> 4 *)

14

The term pure function used in Mathematica is not being used in the same sense as the cited Wikipedia article. In Mathematica it refers to an anonymous function. In the Wikipedia article it is a term extracted by analogy from the increasingly popular term "purely functional" which refers (mainly) to deterministic programming free of side-effects. The ...

13

Yes, this form exists, and was first shown to me by Leonid. It is: Function[Null, (* body with ## *), (* attributes *)] As always the Null may be implicit, so in your application: Function[, Length[Unevaluated@#1]{##2}, HoldFirst][1+2,2+3,3+1] {10, 8}

11

What rm-rf suggested is this: #[[2]]/#[[1]] & /@ (#[[2]] - #[[1]] & /@ Partition[data, 2, 1]) Or some version of it (see g3kk0's answer). This can also be written using Differences: #[[2]]/#[[1]] & /@ Differences[data] If the slope is calculated using the standard $\frac{\Delta y}{\Delta x}$ formula. But we don't have to use an anonymous ...

11

This perhaps: Function[{a, b}, a[#]/b[#] &] @@@ {{a, b}, {c, d}, {e, f}} (* Out: {a[#1]/b[#1] &, c[#1]/d[#1] &, e[#1]/f[#1] &} *) Mr.Wizard's way of writing it (see comment) looks like this in the frontend:

11

foo = With[{f = #0}, (# /. {p___, a, b, c, q___} :> Join[{p, "abc"}, f @ {q}])] & lst = {1, 2, a, b, c, 3, {4, a, b, c}, 5}; foo@lst (* {1, 2, "abc", 3, {4, "abc"}, 5} *) This works because With automatically renames the patterns used in RuleDelayed since both are scoping constructs. Other constructs can be used as well such as RuleDelayed itself: ...

10

Let's read what the docs say: Root[{$f_1, f_2 ,\ldots$}, {$k_1, k_2 ,\ldots$}] represents the last coordinate of the exact vector {$a_1, a_2, \ldots$} such that $a_i$ is the $k_i$th root of the polynomial equation $f_i(a_1, \ldots, a_{i-1}, x)=0$. This, though a bit confusing, is a pretty accurate and straightforward description. Let's assume two ...

10

Two new methods and a comparison of performance. Conceptually I like my second one, but it's slow; similarly I like Anon's second Ratios one, but it's not as fast as the pure function version. The first solution, Anon's fourth, and g3kko's edit are worth looking at if you want to take advantage of Mathematica's efficiencies with vectorized functions and ...

9

Edit: Mr.Wizard helped to refine my old function to: SetAttributes[Through2, HoldFirst] Through2[head_[args___]] := Replace[head, s : _Function | _Symbol :> s[args], -1] This locates the most nested functions and symbols and evaluates their value for the parameter arguments. Below is my older, less robust function: SetAttributes[Through2, HoldFirst] ...

9

Here is one possibility to compute the slope between each pair of adjacent points. I create a list of random points first and use the Sort function sort them by their x-coordinate (First): list = SortBy[RandomReal[{0, 10}, {20, 2}], First] {{0.0612793, 5.82737}, {0.171386, 6.8975}, {0.704354, 8.53224}, {0.798152, 6.39703}, {0.967127, 8.35358}, ...

8

FWIW, I disagree with the answers which state that Function with named arguments and Function expressed using slots (#) are the same thing. Please see the first part of this answer of mine for a partial list of differences. The main difference I want to stress here is that Function-s with named arguments are true (albeit leaky) lexical scoping constructs, ...

8

For the first puzzle, I can only guess. The idea is that Function with named variables is a true lexical scoping construct, in that it cares about the possible name collisions inside the inner scoping constructs, including another Function-s (this is where it is different from Slot- based functions, which are not like that. The price to pay is that ...

8

Why is this happening? How can I speed up my routines without having to put the function explicitly inside Compile? It is happening because Compile has the attribute HoldAll Attributes[Compile] (* {HoldAll, Protected} *) This means, that no evaluation of the arguments will happen. In your case the arguments to your Compile call are {{list,_Real,1}} ...

8

This is a way to resolve the conflict between the two different # instances in your construct, using pure functions only: Select[{1, 2, 3, 4, 5}, Function[i, IntervalMemberQ[Interval[#], i]]] & /@ {{0, 1}, {1, 4}, {3, 4}} (* ==> {{1}, {1, 2, 3, 4}, {3, 4}} *)

7

In can be done in a terse way with nested pure functions: lists = RandomReal[{0, 10}, {3, 10}] {{3.35338, 2.82572, 0.152277, 1.19036, 9.88211, 6.55398, 8.11855, 0.793288, 9.04547, 6.42518}, {4.95417, 7.73982, 5.58323, 3.09912, 5.44546, 8.88474, 2.67437, 8.20605, 4.55918, 1.95303}, {2.53793, 6.67839, 8.71033, 8.4877, 0.634367, 7.99796, ...

7

Because life is more fun with infix: firstPattern ~Reverse~ 2 {a -> A, b -> B, C -> c, two -> one, david -> tom} (The serious point of this answer is that you can use the second parameter of Reverse to determine exactly what levels of the expression you wish to reverse.) Also quite direct and terse: #2 -> # & @@@ firstPattern ...

6

Mapping First over your list will strip off the Function head. Then multiply them together with Apply[Times... and finally Apply[Function... makes the result a pure function. Use the final Apply so the argument to Function is evaluated first as Function has the attribute HoldAll. Apply[Function,{Apply[Times, Map[First,l]]}] Gives... (-1+#1) (#1+#1^2) ...

6

I seem to recall an earlier question addressing this specific aspect (is there a ## equivalent for named parameters) but I cannot find it. Nevertheless... I echo Leonid's answer that there are important differences between pure functions using Slot and/or SlotSequence and named parameters. A primary one is the automatic renaming that occurs with the ...

6

You can use the form Function[{x,y,z}, body] to define a pure function with formal parameters x,y,z ( see Documentation >> Function) Let lists = {ln125, ln126, ln127} = RandomReal[{0, 10}, {3, 10}] (* {{1.72286, 5.24912, 8.87257, 5.77593, 6.31276, 1.77914, 2.06393, 0.328725, 9.46436, 4.96257}, {1.71171, 2.54337, 5.93807, 9.46774, 6.99601, ...

6

I always go with Part before attempting anything else: firstPattern[[All, {2, 1}]] To me at least it seems far simpler and more intuitive than many other approaches.

6

Total[funca[a,#] & /@ #] & /@ {x,y} There are two Function expressions here which I will refer to as inner and outer. The inner function: funca[a,#] & Is Mapped to the sole argument of the outer function. It will transform a list or other expression like this: funca[a,#] & /@ foo[1, 2, 3] foo[funca[a,1], funca[a,2], funca[a,3]] ...

5

How about this: g[n_]:=Function @@ {Slot /@ Join[#, Reverse[#]]&@Range[n]} For a random order: gr[n_] := Function @@ {Slot/@Array[RandomInteger[{1, n}] &, 2 n]} All in all you can replace Range[n] with your own order of integers depending what you want to accomplice.

5

But it doesn't work. Why is that? It becomes visible when you inspect the inner Map only. I replace the slot for the outer function with 1, because we don't need it to see the error b = {1, 2}; c = {1, 2, 3}; Map[f[# &, 1], b] (* {f[#1 &, 1][1], f[#1 &, 1][2]} *) This is not what you expect and when you look a bit closer, you instantly ...

5

Also: list1 = {{"a", 1}, {"b", 2}, {"c", 3}}; f[list1_, list2_] := Select[list1, MemberQ[ToLowerCase /@ list2, #[[1]]] &] f[list1, {"A", "b"}] (* {{"a", 1}, {"b", 2}} *)

5

Just to get an answer on record, the answer to your question is "no". The correct long form of {##2} & @@ f[x1, x2, x3, x4] is Function[{SlotSequence[2]}] @@ f[x1, x2, x3, x4]. Both give {x2, x3, x4}.

5

Here is another option: l = {(#1 - 1) &, (#1^2 + #1) &, (#1^3 - 1) &}; Thread[Times @@ l, Function] (#1 - 1) (#1^3 - 1) (#1^2 + #1) & This has the benefit of not evaluating the body of the functions. For example: l = {(#1 - 1) &, (#1^2 + #1) &, (Print["!"]; #1^3 - 1) &}; Thread[Times @@ l, Function] (#1 - 1) ...

5

I have left bottom part of this answer as a warning against not thinking :) Here is my improvement. It is not so handy but it allows us to specify which argument has to take it's optional value. edit - scoping. f = Module[{x, y, z}, Function[{u, v, g}, x^2 y^4 + z^4 /. {x -> (u /. Null -> 3), y -> (v ...

5

Chop[x, 0.5] evaluates to x because x is symbolic and not a number. Hence your map is equivalent to Plot[...] & /@ {x} which is what you see. The solution then is to prevent Chop from evaluating until it is "inside" Plot and this can be done with Unevaluated: Plot[#, {x, 0, 1}] & /@ {Unevaluated@Chop[x, 0.5]}

Only top voted, non community-wiki answers of a minimum length are eligible