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:29

listMax []     = Nothing
listMax (x:xs) = Just $ foldr (\x y -> if x > y then x else y) x 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

Name: Anonymous 2009-01-27 20:58

>>2
Thanks man
What is Just here

Name: Anonymous 2009-01-27 21:00

Name: Anonymous 2009-01-27 21:14

>>3
I have no idea. I obviously know nothing about Haskell's typing system, so I was trying to learn by example. The only reason I didn't try Maybe was because when I looked it up it talked about monads ands Just, neither of which I understand.

lol (x:xs) = if x > lol xs then x else lol xs
Thanks for the explanation. I kind of expected the runtime would be pig disgusting here. It was more of an attempt to get the function to compile than anything.

Name: Anonymous 2009-01-27 21:41

>>6
It's probably a good idea to read http://learnyouahaskell.com/ to get to grips with this sort of stuff. Maybe is introduced at http://learnyouahaskell.com/making-our-own-types-and-typeclasses#type-parameters (but it's probably best to read it more-or-less in order, at least for the first few chapters).

http://www.haskell.org/haskellwiki/Performance/Accumulating_parameter is also relevant.

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