Map range: Difference between revisions

Content added Content deleted
(→‎{{header|D}}: simplified code)
No edit summary
Line 407: Line 407:
</pre>
</pre>


=={{header|Groovy}}==
<lang groovy>
def mapRange(a1, a2, b1, b2, s) {
b1 + ((s - a1) * (b2 - b1)) / (a2 - a1)
}

(0..10).each { s ->
println(s + " in [0, 10] maps to " + mapRange(0, 10, -1, 0, s) + " in [-1, 0].")
}
</lang>
Output:
<pre>
0 in [0, 10] maps to -1 in [-1, 0].
1 in [0, 10] maps to -0.9 in [-1, 0].
2 in [0, 10] maps to -0.8 in [-1, 0].
3 in [0, 10] maps to -0.7 in [-1, 0].
4 in [0, 10] maps to -0.6 in [-1, 0].
5 in [0, 10] maps to -0.5 in [-1, 0].
6 in [0, 10] maps to -0.4 in [-1, 0].
7 in [0, 10] maps to -0.3 in [-1, 0].
8 in [0, 10] maps to -0.2 in [-1, 0].
9 in [0, 10] maps to -0.1 in [-1, 0].
10 in [0, 10] maps to 0 in [-1, 0].
</pre>
=={{header|Haskell}}==
=={{header|Haskell}}==
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.
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.