Re: Difficulty with patterns
- To: mathgroup at smc.vnet.net
- Subject: [mg122298] Re: Difficulty with patterns
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Mon, 24 Oct 2011 05:13:21 -0400 (EDT)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
On 10/23/11 at 6:24 AM, Paul.McHale at 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