[Haskell-beginners] how to specify type class in type of function?
Daniel Fischer
daniel.is.fischer at web.de
Thu Jan 28 16:26:28 EST 2010
Am Donnerstag 28 Januar 2010 22:06:36 schrieb george young:
> [complete newbie using ghci 6.10.4
> I understand that I should indicate that 'a' is in class Ord, since I
> use lessthan. But what is the syntax? Other style suggestions are
> welcome.
>
> mysort :: [a] -> [a]
mysort :: Ord a => [a] -> [a]
Generally,
function :: (Class1 a, Class2 b) => a -> b -> c
The part of the type signature before the '=>' is called the context, if it
consits of only one constraint, the parentheses can be omitted.
> mysort [] = []
> mysort [x] = [x]
> mysort [x, y] | (x <= y) = [x, y]
>
> | otherwise = [y, x]
>
> mysort l =
> (mysort s1) ++ (mysort s2)
Doesn't work,
mysort [3,2,1,4] ~> [2,3,1,4]
you want merge here instead of (++)
(how to write merge is left as an exercise).
> where
> (s1, s2) = splitAt (div (length l) 2) l
If you have a long list, all those calls to length will take a loong time.
Consider passing it to a helper function which takes the length of the list
as a parameter.
>
> Could not deduce (Ord a) from the context ()
> arising from a use of `<=' at /home/gry/foo.hs:53:17-22
> Possible fix:
> add (Ord a) to the context of the type signature for `mysort'
> In the expression: (x <= y)
> In a stmt of a pattern guard for
> the definition of `mysort':
> (x <= y)
> In the definition of `mysort':
> mysort [x, y]
>
> | (x <= y) = [x, y]
> | otherwise = [y, x]
More information about the Beginners
mailing list