How to find maximum of function outputs with multipe inputs in one function?

Viewed 50

I want a function maxfunct, with input f (a function) and input n (int), that computes all outputs of function f with inputs 0 to n, and checks for the max value of the output.

I am quite new to haskell, what I tried is something like that:

maxfunct f n
  | n < 0 = 0
  | otherwise = maximum [k | k <- [\(f, x)-> f x], x<- [0..n]]

Idea is that I store every output of f in a list, and check for the maximum in this list. How can I achieve that?

1 Answers

You're close. First, let's note the type of the function we're trying to write. Starting with the type, in addition to helping you get a better feel for the function, also lets the compiler give us better error messages. It looks like you're expecting a function and an integer. The result of the function should be compatible with maximum (i.e. should satisfy Ord) and also needs to have a reasonable "zero" value (so we'll just say it needs Num, for simplicity's sake; in reality, we might consider using Bounded or Monoid or something, depending on your needs, but Num will suffice for now).

So here's what I propose as the type signature.

maxfunct :: (Num a, Ord a) => (Int -> a) -> Int -> a

Technically, we could generalize a bit more and make the Int a type argument as well (requires Num, Enum, and Ord), but that's probably overkill. Now, let's look at your implementation.

maxfunct f n
  | n < 0 = 0
  | otherwise = maximum [k | k <- [\(f, x)-> f x], x<- [0..n]]

Not bad. The first case is definitely good. But I think you may have gotten a bit confused in the list comprehension syntax. What we want to say is: take every value from 0 to n, apply f to it, and then maximize.

maxfunct :: (Num a, Ord a) => (Int -> a) -> Int -> a
maxfunct f n
  | n < 0 = 0
  | otherwise = maximum [f x | x <- [0..n]]

and there you have it. For what it's worth, you can also do this with map pretty easily.

maxfunct :: (Num a, Ord a) => (Int -> a) -> Int -> a
maxfunct f n
  | n < 0 = 0
  | otherwise = maximum $ map f [0..n]

It's just a matter of which you find more easily readable. I'm a map / filter guy myself, but lots of folks prefer list comprehensions, so to each his own.

Related