Map range: Difference between revisions
Content added Content deleted
(added Ursala) |
(Go solution) |
||
Line 242: | Line 242: | ||
end function Maprange |
end function Maprange |
||
end program Map</lang> |
end program Map</lang> |
||
=={{header|Go}}== |
|||
For the extra credit, ", ok" is a Go idiom. It takes advantage of Go's multiple return values feature to return a success/failure disposition. In the case of this task, the result t is undefined if the input s is out of range. |
|||
<lang go>package main |
|||
import "fmt" |
|||
// assumes a1 < a2 |
|||
func newRangeMap(a1, a2, b1, b2 float64) func(float64) (float64, bool) { |
|||
return func(s float64) (t float64, ok bool) { |
|||
if s < a1 || s > a2 { |
|||
return 0, false // out of range |
|||
} |
|||
return b1 + (s-a1)*(b2-b1)/(a2-a1), true |
|||
} |
|||
} |
|||
func main() { |
|||
rm := newRangeMap(0, 10, -1, 0) |
|||
for s := float64(-2); s <= 12; s += 2 { |
|||
t, ok := rm(s) |
|||
if ok { |
|||
fmt.Printf("s: %5.2f t: %5.2f\n", s, t) |
|||
} else { |
|||
fmt.Printf("s: %5.2f out of range\n", s) |
|||
} |
|||
} |
|||
}</lang> |
|||
Output: |
|||
<pre> |
|||
s: -2.00 out of range |
|||
s: 0.00 t: -1.00 |
|||
s: 2.00 t: -0.80 |
|||
s: 4.00 t: -0.60 |
|||
s: 6.00 t: -0.40 |
|||
s: 8.00 t: -0.20 |
|||
s: 10.00 t: 0.00 |
|||
s: 12.00 out of range |
|||
</pre> |
|||
=={{header|J}}== |
=={{header|J}}== |