# Tag Info

54

General The conceptual problem with memoized pure functions is that pure functions typically (in fact, normally by their mere definition) do not cause side effects, while memoization necessarily requires side effects (changes of state). What was meant was probably to construct a memoized anonymous (lambda) - functions - this is possible, because the latter ...

33

Per suggestion of rcollyer, I have moved this answer here, with a few modifications / additions. Recursive pure functions (#0) seem to be one of the darker corners of the language. They are mentioned in the documentation of Slot. Here I will review the simple uses, and also show a couple of non-trivial examples of their use , where this is really useful (...

25

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 ...

21

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"}] & @@@ #[[...

20

Try this: Map[If[#==1,Unevaluated@Sequence[],#]&,{1,2,3}] Note the output. The 1 is gone. That's because Unevaluated@Sequence[] puts the empty sequence there, that is, "nothing". ##&[] is a shorthand that can be used in most places for same - ## is the sequence of arguments, & makes it a function to apply to something, [] is that something - ...

19

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

17

You could write something like this: # /. x_Integer :> x (x - 1) & /@ {1, 2, 3} {0, 2, 6}

17

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}

16

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 ...

16

x/## & // FullForm Function[Times[x,Power[SlotSequence[1],-1]]] and Power[a,b,c...] == Power[a, Power[b, c...]] so now it should be clear. This syntax is mentioned in the last bullet point in details of Power documentation.

16

The documentation for Minus states that -x is converted to Times[-1,x] on input. So -Sequence[a,b] == Times[-1,Sequence[a,b]] == Times[-1,a,b] by this definition. Similarly the documentation for Divide states that x/y is converted to x y^-1 on input. and therefore x / Sequence[a,b] == x Sequence[a,b]^-1. Sequence[a,b]^c == Power[a, Power[b,c]]. ...

13

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, 4....

12

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 ...

12

Yes, you can plot it, but not using Plot. For example, you could map the function over a range of values and then use ListLinePlot: With[{xmin = 0, xmax = 4π}, ListLinePlot[f/@Subdivide[##,100],DataRange->{##}]&[xmin,xmax] ] This uses the new function Subdivide with 100 plot points. The reason why Plot requires you to specify a dummy variable is ...

11

To complement WReach's answer, I suggest that you are actually looking for replacement rules. A function with patterns is effected with replacement rules: f[x_Integer] := x(x-1) DownValues[f] {HoldPattern[f[x_Integer]] :> x (x - 1)} You you don't need to actually set this definition (DownValue) to use the same rule. Clear[f] f /@ {1, 2, Sqrt[7],...

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: ...

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

You may already have discovered that something like g[#]& doesn't work - this is because Function has the HoldAll Attribute, so its argument (g[#] in this case) doesn't get evaluated. The solution is to force g[#] to evaluate. Rasher showed what one way to do that, by using Evaluate, whose specific purpose is to force evaluation of arguments that would ...

11

The FullForm of #0[[1]] & is Function[Part[Slot[0], 1]] So when this function is called with no arguments, I believe what happens is that Slot[0] does not evaluate, and then you take the first part of Slot, which is 0. Here it seems that Slot behaves as any other head.

10

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, 2....

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

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}, {1....

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 ...

10

This is really a natural fit for Outer: t = Table[{i, j}, {i, 1, 2}, {j, 1, 2}]; Outer[Apply, {Plus, Subtract, Times, Divide}, t, 2] (* ==> {{{2, 3}, {3, 4}}, {{0, -1}, {1, 0}}, {{1, 2}, {2, 4}}, {{1, 1/2}, {2, 1}}} *)

9

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 Slot-...

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

Imo the most common/readable/flexible way: Function[h, h[#, Log[#]] &][myF] /@ {7, 3} and for fun, less general, as pointed in comments: Through@*#[Identity, Log] &[myF] /@ {7, 3} which can be even shorter, thanks to ybeltukov Through@*#[# &, Log] &[myF] /@ {7, 3}

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

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}} and ...

8

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 ...

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