Re: List difference using patterns and substitutions.
- To: mathgroup at smc.vnet.net
- Subject: [mg71329] Re: List difference using patterns and substitutions.
- From: Yves Klett <yves.klett at googlemail.com>
- Date: Wed, 15 Nov 2006 06:43:28 -0500 (EST)
- Organization: Comp.Center (RUS), U of Stuttgart, FRG
- References: <ejc53g$6qf$1@smc.vnet.net>
Nacho schrieb:
> Hello.
>
> I'm trying to figure how can I build a difference list from another
> using only patterns and rule substitutions.
>
> The idea is to get from a list, another, one element shorter, where
> each value is the substraction of two consecutive elements in the
> original list, that is, from {1,2,3,5,5} get {1,1,2,0}.
>
> I've been thinking about it for a while, and I know several methods
> using a more traditional programming style (with For, for example), but
> I have no idea if it is possible to make it simple and fast with rule
> substitutions.
>
> Any idea?
>
> Thanks in advance.
>
Hi Nacho,
one convenient possibility:
#[[2]]-#[[1]]&/@Partition[{1,2,3,5,5},2,1]
{1,1,2,0}
...one using *only* rules (bitsy awkward, only working for numeric entries):
rule1={a___,b_?NumericQ,c_?NumericQ,d___}->{a,{c-b},c,d};
rule2={l:_List..,x_}->{l};
rule3=List[x_]->x;
{1,2,3,5,5}//.rule1/.rule2/.rule3
{1,1,2,0}
Regards,
Yves