[Haskell-cafe] Empty Input list
Chris Smith
cdsmith at gmail.com
Mon Mar 12 21:46:55 CET 2012
On Mon, Mar 12, 2012 at 2:41 PM, Kevin Clees <k.clees at web.de> wrote:
> what can I do, if a function gets an empty input list? I want, that it only returns nothing.
> This is my source code:
>
> tmp:: [(Int, Int)] -> Int -> (Int, Int)
> tmp (x:xs) y
> | y == 1 = x
> | y > 1 = tmp xs (y-1)
It's not clear what you mean by "returns nothing" when the result is
(Int, Int)... there is no "nothing" value of that type. But you can
add another equation to handle empty lists one you decide what to
return in that case. For example, after (or before) the existing
equation, add:
tmp [] y = (-1, -1)
Or, you may want to use a Maybe type for the return... which would
mean there *is* a Nothing value you can return:
tmp:: [(Int, Int)] -> Int -> Maybe (Int, Int)
tmp (x:xs) y
| y == 1 = Just x
| y > 1 = tmp xs (y-1)
tmp [] y = Nothing
Does that help?
--
Chris Smith
More information about the Haskell-Cafe
mailing list