daily pastebin goal
37%
SHARE
TWEET

[Go] Higher-order function demo.

cwchen Nov 8th, 2017 312 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top