Advertisement
cwchen

[Go] Higher-order function demo.

Nov 8th, 2017
600
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.55 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5. )
  6.  
  7. func apply(arr []float64, callback func(float64) float64) []float64 {
  8.     out := make([]float64, len(arr))
  9.  
  10.     for i, e := range arr {
  11.         out[i] = callback(e)
  12.     }
  13.  
  14.     return out
  15. }
  16.  
  17. func main() {
  18.     arr := []float64{1, 2, 3, 4, 5}
  19.  
  20.     // Square
  21.     sqr := apply(arr, func(n float64) float64 { return n * n })
  22.     fmt.Println(sqr)
  23.  
  24.     // Cubic
  25.     cub := apply(arr, func(n float64) float64 { return n * n * n })
  26.     fmt.Println(cub)
  27.  
  28.     // Inverse
  29.     inv := apply(arr, func(n float64) float64 { return 1.0 / n })
  30.     fmt.Println(inv)
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement