Skip to content

Instantly share code, notes, and snippets.

@caelifer
Last active May 24, 2022 19:32
Show Gist options
  • Select an option

  • Save caelifer/f12b3a11aa2e151894b58dcc25237c08 to your computer and use it in GitHub Desktop.

Select an option

Save caelifer/f12b3a11aa2e151894b58dcc25237c08 to your computer and use it in GitHub Desktop.

Revisions

  1. caelifer revised this gist May 24, 2022. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion generic-fib.go
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    // Live code - https://go.dev/play/p/h2roawBCKH_W
    // Live code - https://go.dev/play/p/EqW-c0gbRqr

    package main

  2. caelifer revised this gist May 24, 2022. 1 changed file with 0 additions and 2 deletions.
    2 changes: 0 additions & 2 deletions generic-fib.go
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,5 @@
    // Live code - https://go.dev/play/p/h2roawBCKH_W

    // You can edit this code!
    // Click here and start typing.
    package main

    import (
  3. caelifer created this gist May 24, 2022.
    55 changes: 55 additions & 0 deletions generic-fib.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    // Live code - https://go.dev/play/p/h2roawBCKH_W

    // You can edit this code!
    // Click here and start typing.
    package main

    import (
    "errors"
    "fmt"
    )

    func main() {
    for _, i := range []int{-1, 0, 1, 93, 94} {
    n, err := Fib(i)
    if err != nil {
    Print(i, err)
    } else {
    Print(i, n)
    }
    }
    }

    // Integer a generic type to represent all supported integer values
    type Integer interface {
    ~int | ~int8 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint32 | ~uint64
    }

    // Print pretty prints result for Fibonacci calculation
    func Print[T Integer](n T, v any) {
    fmt.Printf("Fib(%d) = %v\n", n, v)
    }

    // Fib returns the n-th fibonacci number
    func Fib[T Integer](_n T) (uint64, error) {
    // Sentinel condition
    if _n < 0 {
    return 0, errors.New("bad input")
    }

    // Up-cast provided input
    n := uint64(_n)
    if n <= 1 {
    return n, nil
    }

    var n1, n2 uint64 = 0, 1
    for i := uint64(1); i < n; i++ {
    n1, n2 = n2, n1+n2
    if n2 < n1 {
    return 0, errors.New("overflow")
    }
    }

    return n2, nil
    }