monads

Monads, For Golang, Using Generics
git clone git://git.lair.cx/monads
Log | Files | Refs | README | LICENSE

README (1424B)


      1 go.lair.cx/monads
      2 =================
      3 
      4 Tiny monad utilities for Go, built with generics.
      5 
      6 Requires Go 1.18+.
      7 
      8 
      9 futures
     10 -------
     11 
     12 Also known as Promise.
     13 
     14 ```
     15 job := futures.Run(func() (int, error) {
     16 	// Do something here
     17 	return 42, nil
     18 })
     19 
     20 // Wait until finish
     21 result, err := job.Await()
     22 
     23 // Context-like done
     24 ch := job.Done()
     25 
     26 // Chaining (Mapping)
     27 futures.Map(job, func(v int) (uint32, error) {
     28     return uint32(v), nil
     29 })
     30 // or
     31 futures.FlatMap(job, func(v int) *Future[uint32] {
     32 	if v != 42 {
     33     	return futures.Reject(errors.New("wrong answer"))
     34 	}
     35     return futures.Resolve(uint32(v))
     36 })
     37 ```
     38 
     39 
     40 options
     41 -------
     42 
     43 ```
     44 opt := options.Wrap(42) // Option[int]
     45 opt = options.Map(opt, foo) // Option[int] (foo returns int)
     46 opt = options.Map(opt, func(i int) bool { // Option[bool]
     47 	return false
     48 })
     49 opt = options.FlatMap(opt, func(b bool) Option[int] { // Option[int]
     50 	// b is false, so, this function returns empty.
     51 	if b {
     52     	return options.Wrap(42)
     53 	}
     54 	return options.Empty()
     55 })
     56 opt = options.Map(opt, bar) // opt is empty, so, bar is not called.
     57 ```
     58 
     59 
     60 slices
     61 ------
     62 
     63 ```
     64 slices.Filter([]int{1, 2, 3, 4, 5}, func(v int) bool {
     65     return v > 3
     66 })
     67 // returns []int{4, 5}
     68 
     69 slices.Map([]int{1, 2, 3, 4, 5}, func(v int) uint64 {
     70     return uint64(v)
     71 })
     72 // returns []uint64{1, 2, 3, 4, 5}
     73 
     74 slices.FlatMap([]int{1, 2, 3, 4, 5}, func(v int) []int {
     75     return []int{v, v + 1}
     76 })
     77 // returns []int{1, 2, 2, 3, 3, 4, 4, 5, 5, 6}
     78 ```