I want to create a function absmin which gets a list of floating point numbers and returns the amount of that number which has the smallest distance to 0. We should do it with the function map. My first idea was that the function abs mentioned the problem with amount, but know my question is, how it is possible to create the point with the smallest distance to 0 and that with the map function, can somebody help me?
absmin :: [Double] -> Int
absmin [] = []
absmin (x:xs) = abs (map (x:xs))
Okay, now i changed to:
absmin xs = map abs xs
But with the specification: absmin :: [Double] -> Double
it didn't work, maybe i´m to stupid, but i try and try and it didn't work
CodePudding user response:
You can use the min()
and abs()
functions to find the smallest absolute value in a list of numbers, and then use map()
to apply this value to each element in the list.
CodePudding user response:
If you have a list like [3.14, 2.98, -0.1]
and need to find which number is closest to zero, you need to first map abs
to that list, and then you need to find the min.
Now min
has signature Ord a => a -> a -> a
so it only considers two numbers at the same time. Fortunately we can use a fold to fold this function over our list.
Prelude> absmin = foldr1 min . map abs
Prelude> absmin [3.14, 2.98, -0.1]
0.1