Tag Info

Hot answers tagged

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


15

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}


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


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


11

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.


11

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


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

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


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


9

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


8

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


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


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

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


7

This duplicates the behavior of yours (no effect on zeroes at ends): smoothee=ReplacePart[#, i_ /; i > 1 && i < Length@# && #[[i]] == 0 :> Mean[{#[[i - 1]], #[[i + 1]]}]] &; smoothee[{0, 1, 3, 4, 6, 8, 0, 11, 12, 0, 13, 0}] (* {0, 1, 3, 4, 6, 8, 19/2, 11, 12, 25/2, 13, 0} *) Here's a goofy ...


7

ClearAll[ruleToFunction, f1, f2]; ruleToFunction[func_] := Function[, Evaluate@func[Slot[1]]]; g[x_] := Piecewise[{{0, x < 8.}, {2.5, 8. <= x < 18}, {0, x > 18}}] f1 = ruleToFunction[g] ClearAll[g]; f1@10 f[x_] := x Sin[x^2] f2 = ruleToFunction[f] ClearAll[f]; f2@10


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


6

Here are two possibilities. First, use MovingMap: ClearAll[av]; av[{l_, 0, r_}] := (l + r)/2; av[{_, m_, _}] := m; and then smoothMM[list_] := Join[{First@list}, MovingMap[av, list, 3], {Last@list}] or, you can use in-place assignments: smooth2[list_] := Module[{copy = list, pos = Flatten[Position[list[[2 ;; -2]], 0]] + 1 }, copy[[pos]] = ...


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.



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