# How should I go about writing more functional and list based code? [duplicate]

I've heard that Mathematica is usually faster when the code is list-based and/or uses a functional paradigm.

I'm still working on getting the hang of this; there are a lot of Ifs and Fors that I end up using in more complex code that probably shouldn't be there.

In general how do I go about writing more functional and list based code?

-

## marked as duplicate by The Toad♦Dec 17 '13 at 23:02

This really has nothing to do with Mathematica. It is about functional programming. You basically have to learn to ask the computer what to do and not how to do it. i.e think in a higher abstract level, not implementation level. In addition, you think of functions as objects themselves as well just like data itself. But I think this question belongs to functional-programming tag here programmers.stackexchange.com/questions/tagged/… also see wiki en.wikipedia.org/wiki/Functional_programming –  Nasser Dec 17 '13 at 21:37
@Nasser Thing is, I am reasonably comfortable with Lisp. But Mathematica has its own style, and the problems faced are different. Plus, there are many in-built commands that work well with functional programming or lists. –  Manishearth Dec 17 '13 at 21:40
So this is like asking: I know OO programming in C++, but how to do OO programming in Java? well, you need have to learn new syntax and new commands in Java. The concept of OO programming do not change. Only the syntax changes. Same case here with functional programming and different languages. To learn the syntax of Mathematica is a very wide question. At least that is what I think. But you are free to ask anything you want, and others are free to answer :) –  Nasser Dec 17 '13 at 21:56
@Nasser, with all due respect, you have some one interested in learning Mathematica and you slap them in their face? I don't get it. –  carlosayam Dec 17 '13 at 22:12
Is this something you are after?: alternatives for loops –  Kuba Dec 17 '13 at 22:14

For List manipulation, I find Fold, FoldList, Map and MapThread probably the closest to FP - although there are many others which would be probably harder to achieve in FP but are built-ins in Mathematica. For example, look at Partition or even Transpose. Whereas in Lisp a list of lists is just that, Mathematica can transpose it as it were a matrix if you know that all items have the same length.
Hmm, this is interesting :) I haven't used Fold much but I can see how it would be useful here. (Also, I don't "come from" Lisp, I just am comfy with it but I am much more at ease with procedural things). –  Manishearth Dec 17 '13 at 22:24