Tag Info

Hot answers tagged

51

A "lazy list", "functional style" solution to this problem might look something like this: sIntegers[] ~sMap~ Prime ~sFilter~ palindromicQ ~sTake~ 400 // sList No such notation is built into Mathematica. However, creating such notations is Mathematica's strong suit. Let's do it. First, we need to define the notion of a "stream". Streams are inherently ...


29

It is good practice to check the precedence of code that is not behaving as you expect. One of the easiest ways to do this is to use Ctrl+. to expand the selection outward from the cursor while respecting Mathematica precedence. Converting the expression to StandardForm (Ctrl+Shift+N) will often reveal something about the way Mathematica is parsing your ...


26

Updated with new functions and additional timings Since this question inspired so many answers I think there is as need to compare them. I have included two of my own functions, freely borrowing from previous answers: wizard1[] := Inner[Compose, sel /. {True -> f, False -> Identity}, list, List] wizard2[] := Module[{x = list}, x[[#]] = f /@ ...


26

One way to get the lazy aspect is to use a closure, or the closest way for Mathematica to fake a closure. This is the closures constructor: makePalindromePrimeC[start_: 1] := Module[{p = Prime[start], r}, ((r = NestWhile[NextPrime, p, With[{d = IntegerDigits[#]}, d != Reverse[d]] &]); p = NextPrime[r]; r) &] This creates one: ...


23

Going out on a limb here, but the exhibited expression looks like a brave but flawed attempt to implement the Y-combinator extremely concisely. The Y-combinator is a technical trick used to implement recursion in the lambda calculus. Here is an implementation that stoops to using some symbols: Y[f_] := #[#]&[Function[n, f[#[#]][n]]&] ... and ...


21

As explained by Michael Pilat you cannot create your own compound operators with custom precedence. (You could conceivably write your own parser as Leonid has worked on, or attempt to coerce the Box form with CellEvaluationFunction.) You can however use an existing operator with the desired precedence. Looking at the table Colon appears to be a good ...


20

This is a precedence issue: You may use (value[#[[1]], #[[2]]] = 0.) & /@ tuples instead (ie, explicitly indicate precedence by using brackets). One way to see what is going on is to notice the colour of the # in the notebook. Or select the & symbol, then press Ctrl+. repeatedly. This progressively selects larger chunks of the expression to which ...


20

Since you're learning, I'll show you how to break down your procedural function midpointRK into bare parts and reassemble it in a functional style. FoldList will again be the function of choice here, so since you're already familiar with it, I'll skip the explanation on that. First, observe that ta, tb and h0 are all constants, so there is no need to ...


18

Function has the attribute HoldAll, so the reference to i in the Table expression will not be expanded. However, you can use With to inject the value into the held expressions: Table[With[{i = i}, a[[i]]*Sin[#] &], {i, 3}] (* {a[[1]] Sin[#1] &, a[[2]] Sin[#1] &, a[[3]] Sin[#1] &} *)


17

Is this what you want? l1 = {a, b, c}; l2 = {aa, bb, cc}; sth[#1, #2] & @@@ Tuples[{l1, l2}] {sth[a, aa], sth[a, bb], sth[a, cc], sth[b, aa], sth[b, bb], sth[b, cc], sth[c, aa], sth[c, bb], sth[c, cc]}


16

Due to insistent public demand: If, in a sequence of iterates $\{x,f(x),f(f(x)),\dots\}$, one only needs every $k$-th iterate (say, for $k=3$, you want $\{x,f(f(f(x))),f(f(f(f(f(f(x)))))),\dots\}$), then one can cleverly combine Nest[] and NestList[] like so: NestList[Nest[f, #, k] &, start, n] which yields a list containing the zeroth, $k$-th, ...


16

(#[#] &)[#[#][#] &] You have a function that applies its argument to itself (#[#] &)[8] --> 8[8] We have, on the other hand, a function that applies to itself to make the head it applies to itself (#[#][#]&)[8] --> (8[8])[8] 8[8] is the head of 8[8][8] If we apply the first function to the second one, we get the second function ...


16

You can take advantage of listability. As a rule if a function has the Listable attribute listable operations will be faster than other alternatives such as mapping. {a, b, c} = Transpose[{a, b, c}]; Apply[Plus, x^a*y^b*z^c] or {a, b, c} = Transpose[{a, b, c}]; Total[x^a*y^b*z^c]


16

Implementation Here are my versions. I will start with FoldWhile: Clear[dressInCtr]; dressInCtr[test_, max_] := Module[{ctr = 0}, (++ctr <= max ) && test[##] &] Clear[FoldWhile]; FoldWhile[f_, test_, start_, secargs_List, max_Integer] := FoldWhile[f, dressInCtr[test, max], start, secargs]; FoldWhile[f_, test_, start_, secargs_List] ...


15

Not the "lazy" but shortest: Select[ToString /@ Prime[Range[10^4]], # == StringReverse[#] &] Faster: Select[Prime[Range[10^4]], IntegerDigits[#] == Reverse[IntegerDigits[#]] &] Faster: Pick[#, (# == Reverse[#]) & /@ IntegerDigits /@ #, True] &@ Prime[Range[10^4]] Fastest: (twice faster than the rest, but slower than "lazy") ...


14

I took inspiration from WReach's work of art answer, and made a package that took his ideas and expanded them into a broad, general solution for lazy data in Mathematica. You can find my implemenation on github. To use the package to answer the original question from this post, you'd do something like: palindromicQ[n_] := IntegerDigits[n] /. d_ :> d === ...


14

Good News Everyone! Two-parameter syntax for Fold and FoldList has been (silently) implemented! Taliesin Beynon informs me that this was implemented in 2011, so check your older versions as well. Using version 10: Fold[f, a] FoldList[f, a] f[f[f[1, 2], 3], 4] {1, f[1, 2], f[f[1, 2], 3], f[f[f[1, 2], 3], 4]} And the held expression example: ...


13

Currying I don't know if it is possible to make all functions work in the Currying form (h[x1][x2][..]) but it is at least possible to extend Hold behavior to all arguments which natively that pattern will not have. I will copy my favorite method which was posted here by Grisha Kirilin: SetAttributes[f, HoldAllComplete] f[a_, b_, c_] := Hold[a, b, c] ...


13

If[ #[[2]], f[#[[1]]], #[[1]]] & /@ Transpose[{list, sel}] {f[1], 10, f[100]} this should be a bit faster : If[ Last @ #, f @ First @ #, First @ #] & /@ Transpose[{list, sel}] or using Inner : Inner[ If[#2, f, Identity][#1] &, list, sel, List]


13

Here is an attempt to do this in a more "functional" way, without thought of efficiency: pQ = # === StringReverse@# & @ IntegerString@# &; ppf[x_?PrimeQ] /; pQ[x] := x ppf[x_] := ppf @ NextPrime @ x $IterationLimit = 1*^6; NestList[ppf[# + 1] &, 2, 399]


13

My solution isn't precisely what was asked for: it is the complete parser. At the moment, it is strictly a parser, but the functionality is all ready to be added. Clear[bfinterpreter, bfeval, movf, movb, add1, sub1, write, read, loop, stored, loopdepth, rls] rls = {">" -> movf, "<" -> movb, "+" -> add1, "-" -> sub1, "." ...


12

This version seems to be about twice faster than the fastest so far (generally, as much faster as small is a fraction of selected elements), and about an order of magintude faster when Listable functions are mapped on a numerical list - since it automatically utilizes Map auto-compilation in such cases: ClearAll[conditionalMap]; conditionalMap[f_, lst_, ...


12

I tried to understand the other two solutions, but honestly, I couldn't. So I tried to write a version that is easier to understand. EDIT: I've refactored the code a little, primarily pulling out the "knowledge operators" personKnowsSolution and personKnowsProperty. I'm not really following McCarthy's axiomatization of knowledge, this is just my ad-hoc way ...


12

I wouldn't try to force FoldList, if there are better suited built-ins like RecurrenceTable We could try to simplify your equations first neweqs = { views[n + 1] == views[n] + k inf[n + 1], inf[n + 1] == inf[n] + dinf, dinf == a inf[n] S[n] - b inf[n], S[n + 1] == S[n] + dS, dS == -a inf[n] S[n] }~Eliminate~{dS, dinf} /. ...


12

EDIT To address hard-coded Table and SparseArray limits, and efficiency As pointed out in the comments, hard-coded limits on the Table or SparseArray dimensions may not work in general. Besides being slow, the Table approach quickly eats up system memory for moderate values of max. Here is a variation on WReach's recursive scheme using ReplaceRepeated. With ...


12

You'll want Composition[] or ComposeList[] for the purpose: ComposeList[{f1, f2, f3}, x] {x, f1[x], f2[f1[x]], f3[f2[f1[x]]]} Composition[f3, f2, f1][x] f3[f2[f1[x]]] Since OP wants to be able to feed a list: (Composition @@ {f3, f2, f1})[x] f3[f2[f1[x]]]


11

Nest[Times[#, x] &, x, 5] or Nest[# x &, x, 5] or specifically for your times : Nest[times[x, #] &, x, 5] times[x, times[x, times[x, times[x, times[x, x]]]]]


11

I'm afraid my comment was too obscure to be noticed. Further, I disagree with one premise somewhere in the commentary, and I wish to make a fuller explanation to see if I understand correctly or incorrectly. Finally, I think the question is answered in the documentation on the Standard Evaluation Procedure: Evaluate the head of the expression. ...


11

The problem is just name collisions, that isn't at all abstract and will happen in any programing language, so it would be odd to claim that it's impossible due to the way Mathematica works. The solution is simply to name your parameters when you write your functions so they don't collide, so you write for instance: RegionFunction -> Function[{a1, b1}, ...



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