Message Boards Message Boards

0
|
4619 Views
|
4 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Translating Map and Slot into C?

Posted 11 years ago
What happens when someone is given the task of porting Mathematica code into C or some other language and runs into functions like Map and Slot?  I suppose a specific case is easier to port than a general case.  Maybe I am wrong.  Can someone show me how to write Slot and Map in Mathematica using nothing more sophisticated than Part, If, For, etc.?
POSTED BY: Douglas Youvan
4 Replies
The formatting on my post changed and the code got messed up. I've fixed this so the code should work fine now as it appears on the screen. 

Please try running the code again in a fresh instance of Mathematica.
POSTED BY: Sean Clarke
Sean,

That works  and I understand it.

Thanks,

Doug
POSTED BY: Douglas Youvan
Your question really is the following. If I've written something in the functional programming paradigm, how do I port it to a language in the imperative programming paradigm? The only real answer is that you have to be a good programmer with both paradigms and think about how'd you implement the corresponding code. C doesn't have anonymous functions, so you can't have an equivalent of Slot.

Here's an example piece of functional code in Mathematica:
Map[ #^2+1&, {1,2,3,4,5}]

Here is the equivalent imperative code in Mathematica
f[x_]:= x^2+1
vector = {1, 2, 3, 4, 5};
accumulator = {0, 0, 0, 0, 0};
For[i = 1, i <= Length@vector, i++, accumulator[[i]] = f[vector[[i]]]]

The imperative code is what you'd be able to easily port to C. 

Of course, you can always use a different datastructure than an array to hold the output, which is here called accumulator. 

As a side note, you can sorta do functional programming in C with function pointers, which would allow you to write something like Map above, but that'd be up to you do decide if you wanted to get involved in that mess. 
POSTED BY: Sean Clarke
Sean,

Thank you so much.  This should go in the virtual book.

I am getting: "Set::write: Tag List in {0,0,0,0,0}[] is Protected. >>", but there is nothing obvious to fix.

Doug

Sean,

Two mysterious /  just appeared and now the cell runs red:

Syntax::sntxf: "For[i=1,i<=Length@vector,i++,accumulator[]=f[vector[]]][" cannot be followed by "/i]".
Syntax::tsntxi: "/i" is incomplete; more input is needed.
Syntax::sntxi: Incomplete expression; more input is needed .

Doug
POSTED BY: Douglas Youvan
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract