
Dear Haskell friends, 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) If this function gets an empty list, he throws "Exception: sortAlgo.hs:(18,1)-(21,44): Non-exhaustive patterns in function Main.tmp" *Main> tmp [(1,2),(3,2)] 1 (1,2) *Main> tmp [(1,2),(3,2)] 2 (3,2) *Main> tmp [] 1 *** Exception: sortAlgo.hs:(20,1)-(22,44): Non-exhaustive patterns in function Main.listElementIntInt Thank you for any help ! Best regards Kevin

On Mon, Mar 12, 2012 at 2:41 PM, Kevin Clees
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

Oh, and just to point this out, the function you're writing already exists in Data.List. It's called (!!). Well, except that it's zero indexed, so your function is more like: tmp xs y = xs !! (y-1)
participants (2)
-
Chris Smith
-
Kevin Clees