[Haskell-cafe] getting last char of String
Maciej Piechotka
uzytkownik2 at gmail.com
Sun Jan 2 02:31:36 CET 2011
On Sat, 2011-01-01 at 19:27 +1100, Jesse Schalken wrote:
>
> On Sat, Jan 1, 2011 at 8:54 AM, Felipe Almeida Lessa
> <felipe.lessa at gmail.com> wrote:
> On Fri, Dec 31, 2010 at 6:43 PM, aditya siram
> <aditya.siram at gmail.com> wrote:
> > -- untested and won't work on an infinite list
> > last :: [a] -> a
> > last = head . reverse
>
>
> No definition for last works with infinite lists =).
>
>
> Unless you make the result nullable, of course.
>
>
> maybeLast :: [a] -> Maybe a
>
> maybeLast [] = Nothing
> maybeLast [x] = Just x
> maybeLast (_:xs) = maybeLast xs
>
It may or may not be expected but it may also be written as:
maybeLast' [] = Nothing
maybeLast' (x:xs) = Just (fromMaybe x (maybeLast xs))
The main differences are:
maybeLast (x:_|_) = _|_
maybeLast' (x:_|_) = Just _|_
maybeLast (fix (x:)) = _|_
maybeLast' (fix (x:)) = Just _|_
Regards
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 836 bytes
Desc: This is a digitally signed message part
URL: <http://www.haskell.org/pipermail/haskell-cafe/attachments/20110102/97d96f35/attachment-0001.pgp>
More information about the Haskell-Cafe
mailing list