[Haskell-beginners] function defenition. Do I understand it right?

Brent Yorgey byorgey at seas.upenn.edu
Tue Jul 12 15:15:45 CEST 2011


On Tue, Jul 12, 2011 at 11:43:10AM +0000, Roelof Wobben wrote:
> 
> 
> Oke, 
> 
>  
> 
> So I changed everything to this : 
> 
>  
> 
> 
> halve (xs) | null xs = ([],[])

You do not need this case.  ([], []) is what halve [] already would
have returned even without this case: length [] == 0, so it would
evaluate to (take 0 [], drop 0 []) which is ([], []).

>            | length xs `mod` 2 == 0  = (take n xs, drop n xs)
>            | otherwise = (take (n+1) xs,  drop (n+1) xs)
>   where n= length xs `div` 2 
> 
> 
> main = do
>   putStrLn $ show $ halve [1,2,3,4]
>   putStrLn $ show $ halve [1,2,3]
>   putStrLn $ show $ halve []
> 
>  
> 
> But now I see this message :
> 
>  
> 
> Error occurred
> ERROR line 7 - Unresolved top-level overloading
> *** Binding             : main
> *** Outstanding context : Show b

This message is just because it cannot figure out the type of [] in
'putStrLn $ show $ halve []'.  You can write

  putStrLn $ show $ halve ([] :: [Int])

to give it an explicit type.  It's a bit annoying since we happen to
know that the type of the list makes no difference, but the compiler
can't figure that out.

-Brent



More information about the Beginners mailing list