[clean-list] Newbie Question
Diederik van Arkel
dvanarkel@mac.com
Thu, 19 Sep 2002 00:44:54 +0200
On Thursday, September 19, 2002, at 12:07 AM, Hal Daume III wrote:
> I think the general solution is to report and error if passed an empty
> list. Otherwise, you would need to know the infimum of the type you
> are
> talking about. You could introduce a class to deal with this, but
> that's
> probably too complex.
>
> --
> Hal Daume III
>
> "Computer science is no more about computers | hdaume@isi.edu
> than astronomy is about telescopes." -Dijkstra | www.isi.edu/~hdaume
>
> On Wed, 18 Sep 2002, Wilfried Esken wrote:
>
>> Hello,
>> I tried to learn CLEAN and therefore I read the exercises in the
>> Clean Book.
>> First I made a function MaxofList which should return the maximum
>> value of a
>> list.
>>
>> I tried it this way:
>>
>> maxi :: a a -> a | <, == a
>> maxi a b
>> | a <= b = b
>> | otherwise = a
>>
>> MaxofList [] = 0
>> MaxofList [x] = x
>> MaxofList [x,y] = maxi x y
>> MaxofList [first:rest] =
>> maxi a b
>> where a = first
>> b = MaxofList rest
>>
>>
>> This works fine for a list of integers, but I want to have a function
>> like
>>
>> MaxofList :: [a] -> a
>>
>> This doesn't work because of
>> MaxofList [] = 0,
>> the compiler derives type Int for the function.
>> What is the solution for having a generell typed function in this
>> case?
>>
>> Thank you,
>> Willi
>>
>>
Hal's suggestion is what is implemented in the StdEnv (see maxList in
StdOrdList).
For your version replace the int 0 by the class zero as follows:
zmaxList::!.[a] -> a | Ord a & zero a
zmaxList [a:x] = max1 a x
where
max1:: a !.[a] -> a | Ord a
max1 m [hd:tl]
| hd<m
= max1 m tl
= max1 hd tl
max1 m [] = m
zmaxList []
= zero
Regards,
Diederik