Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Haskell

Name: Anonymous 2009-01-27 20:20

Please help with my Haskell code. It is supposed to return the maximum element in a list but it doesn't work

lol :: [a] -> Nothing | a
lol [] = Nothing
lol [x] = x
lol (x:xs) = if x > lol xs then x else lol xs

Name: Anonymous 2009-01-27 20:55

lol :: [a] -> Nothing | a
Should be [a] -> Maybe a. I'm curious as to where you got the idea that this was possible.

lol (x:xs) = if x > lol xs then x else lol xs
Two problems here. if x > lol xs means that lol xs has to be evaluated before any actual work can be done. Thus it may keep the whole list in memory, since it needs lol xs afterwards as well. The compiler may eliminate the second call to lol xs in which case it's not as bad, but it still wastes stack space because of the second problem, which is that it's not tail recursive.

A similar in spirit, but fixed, version (it would be better to use a fold, however see >>2):
listMax :: [a] -> Maybe a
listMax [] = Nothing
listMax (x:xs) = Just $ iter x xs where
  iter m [] = m
  iter m (x:xs) = iter (if x > m then x else m) xs

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List