Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #5829

Re: Difficulty with patterns

From Bill Rowe <readnews@sbcglobal.net>
Newsgroups comp.soft-sys.math.mathematica
Subject Re: Difficulty with patterns
Date 2011-10-24 09:15 +0000
Organization Steven M. Christensen and Associates, Inc and MathTensor, Inc.
Message-ID <j83ab9$k3c$1@smc.vnet.net> (permalink)

Show all headers | View raw


On 10/23/11 at 6:24 AM, Paul.McHale@excelitas.com (McHale, Paul)
wrote:

>Example 1 uses my old standby, the Table[] function.  Works fine.  I
>am attempting to get better with patterns, so I tried example 2 and
>3.  They work, but gives several errors about use of stringjoin
>needing strings.  What am I doing wrong?

>Error: StringJoin::string: String expected at position 1 in
>StringJoin[n].

>(* Load string from WolframAlpha  *) m
>WolframAlpha["usa",{{"LargestCities:CountryData",1},"ComputableData"
>},
>PodStates->{"LargestCities:CountryData__More","LargestCities:
>CountryData__More"}];

<snip>

>(* example 2 *)
>Clear[n,o,p,q];
>mNew=Cases[m, {{n_String,o_String,p_String},q_} -> { n <>  ", " <> o  <> ", " <>  p,q},Infinity ];
>Grid[mNew,Frame->All]

The problem with the above occurs when the replacement rule is
evaluated. It is evaluated immediately, At that time, n, o, and
p are symbols without assigned values. So, the effect is to
evaluate n <> ", " before n is defined to be a string which
produces the error message. You can avoid this problem by using
RuleDelayed (:>) instead of Rule (->). That is:

Clear[n,o,p,q];
mNew=Cases[m, {{n_String,o_String,p_String},q_} :> { n <>  ", "
<> o  <> ", " <>  p,q},Infinity ];
Grid[mNew,Frame->All]

Will do what you want without the error message. For what it is
worth, I would have done

mNew = m[[1, 2 ;;]]/.{a_List, b_Integer}:>{StringJoin@@Riffle[a,
{", ",", "}], b};
Grid[mNew,Frame->All]

to get the desired output

Back to comp.soft-sys.math.mathematica | Previous | Next | Find similar | Unroll thread


Thread

Re: Difficulty with patterns Bill Rowe <readnews@sbcglobal.net> - 2011-10-24 09:15 +0000

csiph-web