Map range: Difference between revisions
m
→{{header|Haskell}}: (hindent and hlint)
(→Version 4: fixed a syntax error (missing comment delimiter).) |
m (→{{header|Haskell}}: (hindent and hlint)) |
||
Line 890:
Rather than handling only floating point numbers, the mapping function takes any number implementing the <tt>Fractional</tt> typeclass, which in our example also includes exact <tt>Rational</tt> numbers.
<lang haskell>import Data.Ratio
import Text.Printf (PrintfType, printf)
-- Map a value from the range [a1,a2] to the range [b1,b2]. We don't check
-- for empty ranges.
mapRange
mapRange :: (Fractional a) => (a, a) -> (a, a) -> a -> a▼
:: Fractional a
mapRange (a1,a2) (b1,b2) s = b1+(s-a1)*(b2-b1)/(a2-a1)▼
▲mapRange (a1, a2) (b1, b2) s = b1 + (s - a1) * (b2 - b1) / (a2 - a1)
main
main
= do
putStrLn "---------- Floating point ----------"
mapM_ (\n -> prtD n . mapRange (0, 10) (-1, 0) $ fromIntegral n) [0 .. 10]
-- Perform the same mapping over exact rationals.
putStrLn "---------- Rationals ----------"
mapM_ (\n -> prtR n . mapRange (0, 10) (-1, 0) $ n % 1) [0 .. 10]
where
prtD
where prtD :: PrintfType r => Integer -> Double -> r▼
:: PrintfType r
prtD n x = printf "%2d -> %6.3f\n" n x▼
prtR
:: PrintfType r
{{out}}
<pre>---------- Floating point ----------
|