[Haskell-cafe] beginner's problem about lists

Eugene Crosser crosser at average.org
Thu Oct 19 03:01:15 EDT 2006


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?

Eugene

-------------- 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/643e05b1/signature.bin


More information about the Haskell-Cafe mailing list