[Haskell-cafe] Best way to write endsWith

Daniel Fischer daniel.is.fischer at web.de
Sat Oct 21 12:19:41 EDT 2006


Hi John,

long `endsWith` short = (reverse short) `isPrefixOf` (reverse long)

would be a possibility (and might be slightly more efficient). 
And this argument order is much better according to the principle of least 
surprise (a `endsWith` b is naturally interpreted so that b is the suffix).
Regarding your "map ..." problem:

map (`endsWith` "t") ["cat","dog"]

takes two keystrokes more, but preserves meaning in infix application.

Cheers,
Daniel

Am Samstag, 21. Oktober 2006 17:19 schrieb John Ky:
> Hello,
>
> I have this function here:
> > endsWith :: Eq a => [a] -> [a] -> Bool
> > endsWith suffix list
> >
> >   | lengthDifference < 0 = False
> >   | otherwise = (drop lengthDifference list) == suffix
> >
> >   where lengthDifference = (length list) - (length suffix)
>
> Would this be the preferred function argument order?  Or is the reverse
> (ie. endsWith list suffix) better?
>
> I like being able to say "abc" `endsWith` "c", but I also like to be able
> to say map (endsWith 't') ["cat", dog"] but I can't have both.
>
> By the way, is there a better way to write this function to be clearer and
> more efficient?
>
> Thanks
>
> -John



More information about the Haskell-Cafe mailing list