[Haskell-cafe] beginner's problem about lists

Eugene Crosser crosser at average.org
Thu Oct 19 03:07:25 EDT 2006


Sorry, I realized that it does not cover the
  shorter [1..5] (shorter [2..] [3..])
case...

Eugene Crosser wrote:
> On Tue, 10 Oct 2006 falseep at gmail.com wrote:
>> Hi all,
>> I'm trying to implement a function that returns the shorter one of two given
>> lists,
>> something like
>> shorter :: [a] -> [a] -> [a]
>> such that shorter [1..10] [1..5] returns [1..5],
>> and it's okay for shorter [1..5] [2..6] to return either.
>>
>> Simple, right?
> 
> I am still very much of a newbie myself, so sorry for possibly
> un-haskellish style and all, but this seems to work for me:
>
> =====
> data WhichOne = SelUnknown | SelLeft | SelRight
> 
> shorter :: [a] -> [a] -> [a]
> shorter la lb = selectedof $ sorttuple (SelUnknown,la,lb)
> 
> selectedof :: (WhichOne,[a],[a]) -> [a]
> selectedof (SelLeft,la,lb) = la
> selectedof (SelRight,la,lb) = lb
> selectedof (_,la,lb) = error "selectedof unselected tuple"
> 
> sorttuple :: (WhichOne,[a],[a]) -> (WhichOne,[a],[a])
> sorttuple (_,(a:xa),(b:xb)) = prefixt a b (sorttuple (SelUnknown,xa,xb))
> sorttuple (_,[],[]) = (SelLeft,[],[])
> sorttuple (_,(a:xa),[]) = (SelRight,(a:xa),[])
> sorttuple (_,[],(b:xb)) = (SelLeft,[],(b:xb))
> 
> prefixt :: a -> a -> (WhichOne,[a],[a]) -> (WhichOne,[a],[a])
> prefixt a b (w,la,lb) = (w,(a:la),(b:lb))
> =====
> 
> What do you think?

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 252 bytes
Desc: OpenPGP digital signature
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20061019/ad333edb/signature.bin


More information about the Haskell-Cafe mailing list