Mathematica Programming » Functional Programming

Map / Scan

Note that often we can even one-up Table and Do in terms of simplicity, while losing no performance. Map and Scan pass an argument from a list to a function, much as Table and Do iterate over a range or list:

 Table[PrimeQ@i,{i,10^6}]//
AbsoluteTiming//First
 0.369371`

compared to

 Map[PrimeQ,Range[10^6]]//
AbsoluteTiming//First
 0.3625`

Even better, though, Map has a more compact in-line syntax:

 PrimeQ/@Range[10^6]//
AbsoluteTiming//First
 0.374421`

Over time you will start thinking in this new syntax. Rather than “map prime-q over range of 10^6” you will start to think “prime-q slash at range of 10^6”.

Note that both Map and Table generate output, while their equivalents Scan and Do don’t. Even though Scan does not have in-line syntax it is worth getting to know, as it can sometimes be more efficient than Do and is, of course, vastly more efficient than For