Advertisement
SetKaung

A try at Maybe monad in Go

Oct 24th, 2023
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.64 KB | Source Code | 0 0
  1. package main
  2.  
  3. import (
  4.     "errors"
  5.     "fmt"
  6.     "golang.org/x/exp/constraints"
  7. )
  8.  
  9. type Maybe[T any] struct {
  10.     Value T
  11. }
  12.  
  13. type None struct {
  14. }
  15.  
  16. func (n None) Unwarp() any {
  17.     return errors.New("empty")
  18. }
  19.  
  20. func (m Maybe[T]) Unwarp() any {
  21.     return m.Value
  22. }
  23.  
  24. type Option interface {
  25.     Unwarp() any
  26. }
  27.  
  28. func division[T constraints.Float](m, n int) Option {
  29.     if n == 0 {
  30.         return None{}
  31.     }
  32.     result := T(m) / T(n)
  33.     return Maybe[T]{result}
  34. }
  35.  
  36. func main() {
  37.     divide := division[float64](10, 20)
  38.     value := divide.Unwarp()
  39.     switch value.(type) {
  40.     case error:
  41.         fmt.Println("Can't divide.")
  42.         break
  43.     default:
  44.         fmt.Println(value)
  45.     }
  46. }
  47.  
Tags: go monad
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement