[Haskell-cafe] Typing problems with basic arithmetic - help!

ChrisK chrisk at MIT.EDU
Fri Sep 23 21:01:24 EDT 2005


Well...your recursion will fail if (a:r) is matched against the empty
set.  That will trigger your Exception.

So does your code avoid this ?  No, it does not.

cus 2 [1,2,3,4,5] recurses
to cus 1 [2,3,4,5]
   to cus 0 [3,4,5]
      to cus (-1) [4,5]
         to cus (-2) [5]
            to cus (-3) [] ---Exception

You need a n<=0 guard case AND an empty list base case

chooseuniqueset _ [] = []
choosenonuniqueset n (a:r)
     | n<=0 = []             -- This needs to be the first guard

Also, you're sorting is poor.  The first case sorts too much and the
second case does no sorting.

Marcin Tustin wrote:
> For some reason the following code is producing an error message from ghci that the the patterns are non-exhaustive. Does anyone have any idea why that could be, given that the patterns are, at least in my meaning, provably exhaustive?
> 
> choosenonuniqueset n (a:r)
>     | (length r) >  (n-1) = [ (sort (a:x)) | x <- (choosenonuniqueset (n-1) r)] 
>                             `union`
>                             [ (sort (a:x)) | x <- (choosenonuniqueset n r)]
>     | (length r) == (n-1) = [a:r]
>     | (length r) <  (n-1) = []
> 
> Error message is:
> 
> *Main> :reload
> Compiling Main             ( birthday.hs, interpreted )
> Ok, modules loaded: Main.
> *Main> choosenonuniqueset 2 [1..5]
> *** Exception: birthday.hs:(22,0)-(27,29): Non-exhaustive patterns in function choosenonuniqueset
> 
> *Main> choosenonuniqueset 5 [1..5]
> [[1,2,3,4,5]]
> *Main>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe


More information about the Haskell-Cafe mailing list