Last active
          December 14, 2021 16:04 
        
      - 
      
- 
        Save jakecoffman/1db38b3cf77f549e6b77 to your computer and use it in GitHub Desktop. 
    Example of functional programming in Golang.
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | package main | |
| import ( | |
| "constraints" | |
| "fmt" | |
| ) | |
| func main() { | |
| fmt.Println(Sum(1, 2, 3, 4)) | |
| fmt.Println(Sum("1", "2", "3")) | |
| } | |
| func Map[T any](operation func(p T) T, is ...T) []T { | |
| r := make([]T, len(is)) | |
| for index, value := range is { | |
| r[index] = operation(value) | |
| } | |
| return r | |
| } | |
| func Reduce[T any](operation func(a, b T) T, is ...T) T { | |
| var r T | |
| for index, value := range is { | |
| if index == 0 { | |
| r = value | |
| } else { | |
| r = operation(r, value) | |
| } | |
| } | |
| return r | |
| } | |
| func Add[T constraints.Ordered](a, b T) T { | |
| return a + b | |
| } | |
| func Sum[T constraints.Ordered](i ...T) T { | |
| return Reduce(Add[T], i...) | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Now that generics are here there's less of a performance hit doing functional programming! I've updated the gist.