Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: How to hold a form and convert it to a string

  • To: mathgroup at smc.vnet.net
  • Subject: [mg93970] Re: How to hold a form and convert it to a string
  • From: David Bailey <dave at removedbailey.co.uk>
  • Date: Sun, 30 Nov 2008 06:58:53 -0500 (EST)
  • References: <ggog1m$s6g$1@smc.vnet.net>

Patrick Scheibe wrote:
> Hi,
> 
> I'm sure it's a simple question but I don't get it. I want to transform
> the expression
> 
> a*q + b*q^2 + c*q^3
> 
> into a C-Code form
> 
> "a*q + b*q*q + c*q*q*q"
> 
> With the rule
> exp //. (Power[q_, n_] :> Times@@Array[q &, n])
> for the transformation of the Power of q,
> the expression is instantly reevaluated to the first form (as I expected
> it). I could transform the complete first expression to a C-Form-String
> and manipulate this. This would look like
> 
> f[exp_] := StringReplace[ToString@CForm[exp],
>   "Power(" ~~ q_ ~~ "," ~~ n_ ~~ ")" :>
>    StringJoin[Riffle[Array[ToString@q &, ToExpression[n]], "*"]]]
> 
> Isn't there a more stylish way?
> 
> Cheers
> Patrick
> 
One way to do this is to replace Times with Star. This has nearly the 
same precedence, but no built in meaning. After conversion to a string, 
a simple StringReplace can swap "\[Star]" into "*".

David Bailey
http://www.dbaileyconsultancy.co.uk


  • Prev by Date: Re: DeleteCases and multiple patterns
  • Next by Date: Re: v.7.0 issues
  • Previous by thread: Re: How to hold a form and convert it to a string
  • Next by thread: Re: Mathematica 7: PieChart: opacity of a sector