Haskell function seeking further explanation -
i've been trying create haskell function gets largest odd integer in list. sounds easy, , sure thought looks i'm stuck! here code, far returns largest number in list including both odd , numbers:
maximum :: (ord a) => [a] -> maximum [x] = x maximum (x:xs) = max x (maximum xs)
thank in advance help!
first of - if have elements in list have problem, function not total (i.e. produces error) - best modify type of result account possibility:
also others have mentioned - odd
requires constraint integral
instead of ord
.
maximodd :: integral => [a] -> maybe maximodd xs = case filter odd xs' of [] -> nothing xs' -> (maximum xs')
the function filter odd
removes non-odd elements (i.e. numbers) - pattern match on result account failure.
if want work original function code gets lot more tricky:
maximum :: integral => [a] -> maximum [x] = x maximum (x:xs) = let y = maximum xs in if x >= y && odd x x else if x < y && odd y y else ??
hmm - don't think can make work - maybe helper function.
maximum :: integral => [a] -> maybe maximum xs = maximum' nothing xs maximum' nothing (x:xs) = if odd x maximum' (just x) xs else maximum' nothing xs maximum' (just y) (x:xs) = if odd x maximum' (just $ max x y) xs else maximum' (just y) xs maximum' x _ = x
which more complicated - , haskell not known being complicated ;)
Comments
Post a Comment