Haskell - "Non-exhaustive patterns" error with a function using list -


i'm trying make function in haskell know if elements in list of list have same length. (i've search answers in previous posts none of them works).

samelength :: [[t]] -> string samelength [] = "empty list" samelength [[items]]     | , $ map (\x -> length x == (length $ head [[items]])) [[items]] = "same length"     | otherwise = "not same length" 

the problem doesn't work :

*main> :l test.hs [1 of 1] compiling main             ( test.hs, interpreted ) ok, modules loaded: main. *main> samelength [] "empty list" *main> samelength [[1,2],[3,4]] "*** exception: test.hs:(2,1)-(5,39): non-exhaustive patterns in function samelength  *main> samelength [[1,2]] "*** exception: test.hs:(2,1)-(5,39): non-exhaustive patterns in function samelength 

i don't see problem. treat case in parameter empty list , in not. wrong ? did miss ?

thanks :)

you have many [..] in here:

samelength [[items]]  

(as silvio explained well) - try

samelength items  

instead.

further a == a, don't have check if length of head same length of head` (of course) , recommend doing this:

samelength :: [[a]] -> bool samelength []     = true samelength (h:tl) = ((length h ==) . length) tl 

as think bool result more useful , natural

how work?

all takes predicate , list , checks if predicate holds each element of list - (length h ==) . length = \xs -> length h == length xs predicate checks if given list xs has same length head-list h - due remark above have check tail-list tl

remark

you can argue if elements of empty list should have the same length - think answer should yes ;)

examples

prelude> samelength [[1,2],[3,4]] true prelude> samelength [[1,2],[3,4,5]] false prelude> samelength [[1,2]] true prelude> samelength [] true 

in case concerned performance

(or not point-free style)

samelength :: [[a]] -> bool samelength []     = true samelength (h:tl) = let l = length h                     in (\xs -> length xs == l) tl 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -