Apply card, but only for temporary use

For function:

func :: [Int] -> Int
func x = minimum (map (+5) x)

And input: func [1,10].

I am trying to get the conclusion 1, since 1+5below 1+10, however, I can only figure out how to derive the value after applying the matching function, while I want only the mapping that is applicable to my use minimum, and the output is one of the original inputs.

How can I use the card temporarily until I find what I want and then return a pre-configured version of this value?

+4
source share
3 answers

, Data.List.minimumBy. , , , . .

> :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 . , , , , :

comparer :: Int -> Int -> Ordering
comparer x y = ...

.

func x = minimumBy comparer x

func = minimumBy comparer
+4

minimumBy (comparing f) ( f (+5) )

minimumBy :: (a -> a -> Ordering) -> [a] -> a

comparing :: Ord a => (b -> a) -> b -> b -> Ordering

+2

minimumBy, . , (+5) (). .

[4,3,2,1]

compare 4 3 => compare (4+5) (3+5) => compare 9 8 => GT
compare 3 2 => compare (3+5) (2+5) => compare 8 7 => GT
compare 2 1 => compare (2+5) (1+5) => compare 8 7 => GT

, (3+5),(2+5) .

(+5), . , , :

map (\x -> (expensive x, x)) [4,3,2,1]

, expensive (+5) . :

snd $ minimumBy (comparing fst) $ map (\x -> (expensive x, x)) [4,3,2,1]

snd $ minimum $ map (\x -> (expensive x, x)) [4,3,2,1]

, , [4,3,2,1] , , expensive .

However, note that the latter will not only return a random list item [4,3,2,1]that minimizes expensive, but it will be the minimum such item. That is, when expensive x == expensive y, the function minimumbreaks the connection by comparing xit ydirectly. The first does not give such a guarantee.

0
source

All Articles