[Haskell-cafe] Producing MinimumValue

Steve Schafer steve at fenestra.com
Thu Jul 19 14:18:46 EDT 2007


On Thu, 19 Jul 2007 10:55:19 -0700 (PDT), you wrote:

>The question suggests to use some functions defined in the section, and one
>of them is iSort.

Aha. Well, that one certainly lends itself better to this particular
proplen than either map or filter.

>minimumValue :: [Int] -> Int
>minimumValue ns = head (iSort ns)

If I were going to use a sort, then yes, that's the way I would do it.
Of course, sorting isn't the best way to solve the problem, as sorting
will always be at least O(n * log n), whereas a more straightforward
algorithm would be O(n).

>The other question is to test whether the values of allEqual on inputs 0 to
>n are all equal.  Again, I defined the method but not sure if its concise?
>
>allEqual :: [Int] -> Bool
>allEqual xs = length xs == length (filter isEqual xs)
>	where
>	isEqual n = (head xs) == n

Simple recursion is probably the most conceptually straightforward
approach here. One little difficulty with this problem (and with
minimumValue, too) is that the problem isn't completely specified,
because we don't know what answer we're supposed to give when the list
is empty. Let's assume that allEqual is supposed to return True on an
empty list. In that case, we can write it like this:

 allEqual :: [Int] -> Bool
 allEqual (x1:x2:xs) = ???
 allEqual _          = ???

where the two ???s are left as an exercise for the reader.

-Steve


More information about the Haskell-Cafe mailing list