# Tag Info

96

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

89

Preamble I had a talk devoted specifically to this topic, on Second Russian WTC in 2014. Unfortunately, it is in Russian. But I will try to summarize it here. Since this post is becoming too long, I decided to split it to several smaller ones, each dedicated to some particular set of methods / techniques. This one will contain a general / conceptual ...

62

Managing the complexity, II: controlling complexity on the smaller scale There are a few things you can do to control and reduce the complexity of your code, even on the small scale - long before you move to packages and split code into several files. Effective use of the core data structures This is probably the first thing to mention. The most important ...

53

These three functions are similar (speaking commonly), and in some applications any of them could be used, yet they have very different special applications. Rudimentarily: Map wraps (sub)expressions in a given Head, and returns the modified input Apply replaces Heads in (sub)expressions, and returns the modified input Scan "visits" (sub)expressions, ...

50

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

43

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

43

Here are some advices from my experience. Explore new ideas with the Mathematica frontend. Don't hesitate to use sections and subsections in the frontend to structure your work and experiment various possibilities. When you have instructions that work, package them into functions, still in the frontend. It's practical to select all the useful instruction ...

40

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] &} This issue will be present not only for Function but for all ...

36

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

36

Managing the complexity III: using powerful abstractions In this section I will list a few techniques which allow one to write more modular code and better separate the concerns, by using certain powerful abstractions provided by or possible to have in the Mathematica. Higher-order functions These are functions which take other functions as arguments. In ...

34

Clearly the @ notation is inspired by the usual mathematical notation for function composition. f@g[x] looks very similar to the mathematical notation $(f\circ g)(x)$. But it is important to understand that @ does not denote function composition. In mathematical notation $f\circ g$ is also a function. In Mathematica f@x is simply a different way to ...

33

Edit: version 11.0 update. Now it is superset of TypeSystem$OperatorForms. It now also includes operator forms that have different names than the functions they're currying, like EqualTo. One can find these functions in the documentation by keywords "operator form" Select[Names@"*", StringMatchQ[ToString@ToExpression[# <> "::usage"], "*operator ... 32 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 ... 31 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 === ... 31 Updated with new functions and additional timings Since this question inspired so many answers, I think there is a 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 /@ x[[#]];... 29 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 ... 28 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. As Naitree notes this is now documented in 10.0.2: 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 ... 26 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,$2k$-... 26 Imho some important things to translate between Matlab and Mathematica: "everything is a matrix (or inefficient)" vs. "everything is an expression" indexing into arrays: : vs. All indexing into arrays: j:i:k vs. j;;k;;i constructing ranges: j:i:k vs. Range[j,k,i] column-major vs. row-major!: mat(:) vs. Flatten[Transpose[mat]] or (mat')(:) vs. Flatten ... 25 You could use Apply at the first level: Times @@@ listA 25 I thought that for any function f we could use "f" interchangeably with "f[#]&". That is only true if the function has no special attributes. Function effectively removes those attributes, and all other special behaviour. For example, Hold[1 + 1] (* Hold[1 + 1] *) Hold[#] &[1 + 1] (* Hold[2] *) Function[x, Hold[x], HoldAll][1 + 1] (* Hold[1 + 1]... 24 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] :... 24 This answer is based on the original poster's statement that he has been using Mathematica for six months, and is now trying to build something a bit more complex. I do not take this to mean a large project in the sense that an application developer would use the word. The notebook interface is really easy to experiment in, and I know that when I had used ... 24 test = a[b[c[d]]]; Fold[ Construct, (* or Compose, see [1] *) Level[test, {-1}, Heads -> True] ] a[b][c][d] [1] - Is there a name for #1@#2&? Alternatively, thanks to OP and Mr.Wizard: HeadCompose @@ Level[test, {-1}, Heads -> True] 22 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") Select[Pick[... 22 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 ... 22 Short answer: See Heike's post. Longer version: There are a couple of functions in the functional programming toolbox that are so common that they've gotten their own symbols. One of them is Apply, which takes a list and uses its elements as function arguments: Apply[f, {a, b, c}] f[a, b, c] The shorthand notation for this would be f @@ {a, b, c}. ... 22 There is a global variable that purports to contain a list of operator forms, TypeSystem$OperatorForms. I say "purports", because the list is missing some of the forms found by @ybeltukov's method. But to its credit, it correctly identifies the operator form of ReplaceAll which is mentioned in neither a usage message nor the documentation, and also ...

22

From version 10.3 you can use WolframLanguageData. WolframLanguageData[EntityClass["WolframLanguageSymbol", "Curryable"]] As of 11.0, this appears to be the most reliable solution: Unfortunately, this method is not perfect either: at least TuringMachine is missing from it. Hope this helps.

22

AbsoluteTiming[Total[Range[1, 100000000]^2]] (* {26.0686, 333333338333333350000000} *) or AbsoluteTiming[#.# &@Range[1, 100000000]] (* {35.2883, 333333338333333350000000} *) or AbsoluteTiming@Total[Range[1, 100000000] /. {x_ -> x^2}] (* {30.9893, 333333338333333350000000} *) To compare with @corey979 solution out = 0; Do[out = out + i^2, {i, 1, ...

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