Given a function:
func :: [Int] -> Int
func x = minimum (map (+5) x)
And an input:
I'm trying to get the output
1+5 is lower than
1+10, however, I can only work out how to output the value after the mapping function has been applied, whereas I only want the mapping to apply to my
minimum usage and the output to be one of the original inputs.
How can I use a map temporarily, until I've found what I wanted, then return the pre-mapped version of that value?
Best How To :
There are several ways, but the best is probably to use
Data.List.minimumBy. It takes a function that can compare two elements, then finds the smallest element using that comparison function. It's pretty much purpose built for your situation. It's type is
> :type minimumBy
minimumBy :: (a -> a -> Ordering) -> [a] -> a
> :info Ordering
data Ordering = LT | EQ | GT -- Defined in 'GHC.Types'
-- A bunch of instances that don't really matter here
Ordering is just a basic sum type with three no-argument constructors. Their names are pretty self explanatory, so all you need to do is pass it a function that returns one of these values:
comparer :: Int -> Int -> Ordering
comparer x y = ...
I'll leave the implementation to you. You can then use it as
func x = minimumBy comparer x
func = minimumBy comparer