Tag Info

Hot answers tagged

43

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


23

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


22

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


22

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


20

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


17

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


16

Perhaps something like this: list = {1, 10, 100}; sel = {True, False, True}; MapThread[f, {list, sel}] (* {f[1, True], f[10, False], f[100, True]} *) So, like: f[i_, True] := f[i] f[i_, False] := i MapThread[f, {list, sel}] (* {f[1], 10, f[100]} *)


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


16

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


15

(#[#] &)[#[#][#] &] 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 ...


15

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


15

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


15

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] &} *)


15

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]


14

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

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


13

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


12

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


12

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]


12

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


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

How about something unconventional? Transpose[{list, sel}] /. {x_, y_} :> (f^Boole[y])[x] /. 1[x_] :> x (* {f[1], 10, f[100]} *) Again, another unconventional solution: Transpose[{list, sel}] /. {x_, y_} :> (y /. {True -> f, False -> Identity})[x]


10

Two more ways: parti1[a_, p_] := SortBy[a, {Sign[# - p] &, # == # &}] or parti2[a_, p_] := Join[Select[a, # < p &], {p}, Select[a, # >= p &]] With a = {3, 5, 6, 7, 2, 1, 2}; (* and *) p =3 both give {2, 1, 2, 3, 5, 6, 7} Update: While the two methods above and Heike's two methods give exactly the same results, ...


10

Let me first redefine your relax to return a list as: Clear@relax1 relax1[j_List, i_Integer] := MapAt[Mean[Nearest[j, #, 4]] &, j, i] Then, the algorithm can be written in a functional way without state variables using Fold and NestWhile as follows (if I understood your intentions correctly): With[{indx = Range@Length@#}, NestWhile[Fold[relax1[#1, ...


10

You could do Outer[f, la, lb] as already suggested. Alternatively you could do Partition[Apply[f, Tuples[{la, lb}], {1}], Length[la]] or Table[f[ai,bi],{ai,la},{bi,lb}] or Array[f[la[[#1]], lb[[#2]]] &, {Length[la], Length[lb]}]


10

The problem is that you forget that you assign something to x and use this! func[{x_, y_}] := Module[{xx = x + 2 y}, {xx, y + 2 xx}]; NestList[func, {1, 1}, 5] But when you think about this short snip of code a bit longer, then you see the following: First you set x = x + 2 y and then you use this value in the next line. Basically, we can show this by ...


10

Without Module : f[{x_, y_}] := {x + 2 y, 2 x + 5 y} NestList[ f, {1, 1}, 5] {{1, 1}, {3, 7}, {17, 41}, {99, 239}, {577, 1393}, {3363, 8119}} or exactly NestList[f, {1, 1}, 5] // Rest // Column Module is not recommended when we encounter a long list (or deep nesting) see e.g. Why modules with no variables ?.



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