Re: RE: Re: Test of a pure function
- To: mathgroup at smc.vnet.net
- Subject: [mg34070] Re: [mg34046] RE: [mg34041] Re: [mg34010] Test of a pure function
- From: Sseziwa Mukasa <mukasa at jeol.com>
- Date: Wed, 1 May 2002 08:00:46 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
On Sunday, April 28, 2002, at 03:46 AM, DrBob wrote:
> I like this solution a lot and can't think why I missed the idea...
> probably because I'm not used to thinking in terms of patterns yet.
>
> HOWEVER, if the list isn't always sorted and you want to find adjacent
> list elements that bracket x, a solution more like mine is required.
>
> Bobby
If the list isn't sorted are you sure a solution exists? There may not
be any bracketing pairs in the list eg. lst={3,2,1} cannot bracket any
value x according to the condition lst[[n-1]]<=x<lst[[n]] for some n.
The following recursive function will check successive pairs of the list
until either a solution is found or no pairs remain. If no bracketing
interval is found it returns the length of the list, otherwise it
returns the index of the first element of the bracketing pair:
bracket[lst_List,val_] :=
If[First[lst]<=val<lst[[2]],1,If[Length[lst]>2,1+bracket[Rest[lst],val],2]
]
To express this as a pure function simply replace lst by #1, val by #2
and bracket by #0:
If[First[#1]<=#2<#1[[2]],1,If[Length[#1]>2,1+#0[Rest[#1],#2],2]]&
Regards,
Sseziwa