Mathematica Mastering Mathematica Functions: Recursive Vector Squaring & List Sorting

AI Thread Summary
The discussion focuses on writing functions in Mathematica to square elements in a vector recursively and to sort a list of numbers. The user initially attempts to create a squaring function but encounters issues with the syntax and logic. Key problems identified include the need to use delayed assignment (:=) instead of direct assignment (=) for the function definition, correcting the indexing from list[n - 1] to list[[n - 1]], and clarifying the purpose of the Sum function in the context of recursion. Additionally, for the sorting function, it's emphasized that the user can directly call sort[x] with x being a defined list, as the function will process whatever list is passed to it. Overall, the discussion highlights the importance of proper syntax and clarity in function definitions in Mathematica.
Physics_rocks
Messages
12
Reaction score
0
Hi guys ,

I'm a little new with Mathematica and I'm trying to write down some functions.
the first one is writing a functions that square the elements in a vector , recursively ,
using patterns .

so , I tried this one :
x = Range[1, 10];
sq[0,list_]=list^2;
sq[sum_,list_] := Sum[sum*sq[sum, list[n - 1]], _list]


but it isn't working . what's the problem ? 2. The second function is writing a function that sorts a list of numbers , by checking each time two numbers that are adjacent .

if I write this : sort[list_] :=
how can I tell mathematica that I want to use an actual list of numbers ? can I say list ?

thank you
 
Physics news on Phys.org
There seem to be multiple problems.
First of all, the assignment in the second line should probably be delayed (:= instead of =) because you want to substitute "list" for whatever value is passed. Also, list[n - 1] is a function call, you meant list[[n - 1]]? Anyway, what is n in that expression? Finally, what are you doing with the "Sum" expression? Sum[f[x], {x, a, b}] sums the values of f[x] for a <= x <= b.

Can you maybe explain more clearly what you want the function to do (e.g. if you input x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, do you want it to output {1, 4, 9, 16, 25, 36, 49, 64, 81, 100} ?)

2) How do you mean: "use an actual list of numbers"? You can call sort[x] (where x is defined as in your first example). In the expression after ":=", the expression "list" will contain whatever list you input (so if you call sort[x], then the definition is executed where list = x).
 

Similar threads

Replies
4
Views
2K
Replies
13
Views
2K
Replies
4
Views
4K
Replies
6
Views
4K
Replies
1
Views
2K
Replies
22
Views
3K
Replies
1
Views
2K
Back
Top