Message Boards Message Boards

1
|
5528 Views
|
7 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Changing Head of an Expression

Posted 9 years ago

Hello everyone,

I'm trying to define a Function, which changes the Head of an Expression to be List. i.e.: $$ f[a,b,c,d,e] \mapsto List[a,b,c,d,e] $$ I found a way to change Plus into List, but it's quite long:

chang[var__] := ToExpression[ StringReplacePart[ToString[FullForm[var]], "List", {1, 4(Plus has 4 letters)}]]

Can you think of doing this in a more general & elegant way for arbitrary Head f? Thank you for your reply,

Best regards, Josip

POSTED BY: Josip Turkalj
7 Replies
Posted 9 years ago

Well thank you for your help!!

I think I made this FullForm-mistake somehow also in the pre-fix version already, too. Without FullForm it works well in one line

Apply[List, Expand[Product[1 + C[i], {i, 1, 2}]]]
POSTED BY: Josip Turkalj
Posted 9 years ago

Now an additional problem came up. How can I combine the two lines into one?

Product[1 + C[i], {i, 1, 2}] // Expand // FullForm
Out[-1] // Apply[List]

The simple Code doesn't do it:

Product[1 + C[i], {i, 1, 2}] // Expand // FullForm // Apply[List]

I once learnt it, but meanwhile it slipped my mind what the reason for this problem is and the way out. I also forgot where I could look it up. Could you help me out, please?

POSTED BY: Josip Turkalj

I would suggest that you not use things like postfix operators (eg, //) and so on until you have used a function in several ways first. Your example is not using Apply correctly. The direct way to do this (and avoiding using things like Out[-1] -- name your expressions and act on them by the name you;ve given them).

First,

result = Expand[Product[1 + C[i], {i, 1, 2}]]

then

Apply[List, result]

Do not use FullForm in defining your expression. FullForm is a way of printing out a result, but the head of the result is FullForm.

Head[FullForm[result]]

gives

FullForm

not Plus.

POSTED BY: David Reiss
Posted 9 years ago

OK :) Thank you!

POSTED BY: Josip Turkalj

The only problem with what you tried is that you used the arguments backwards. Here is what you want to do for your case (and, sorry, I should have given you an example!):

Apply[List, f[a, b, c, d, e]]

then gives

{a, b, c, d, e}

Note that there is a very common shorthand for using Apply in this simple way. it's to use @@ in the following way:

List @@ f[a, b, c, d, e]
POSTED BY: David Reiss
Posted 9 years ago

Thank you for your suggestion. How do I have to use Apply for the problem above? I thought of this:

Apply[f[a, b, c, d], List, {1}]

but this computes solely »List« as Output ?!

POSTED BY: Josip Turkalj

The function that you are looking for is Apply:

http://reference.wolfram.com/language/ref/Apply.html

POSTED BY: David Reiss
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