2025-10-14

Crafting IsOdd()

Mutually Recursive

Crafting Interpreters chapter 8 shows us an interesting way to implement IsOdd() & IsEven() by mutually calling each other recursively.

Implementation in Go

package main

import "fmt"

func isOdd(i int) bool {
  if i == 0 {
    return false
  } else {
    return isEven(i - 1)
  }
}

func isEven(i int) bool {
  if i == 0 {
    return true
  } else {
    return isOdd(i - 1)
  }
}
func main() {
  fmt.Println(isOdd(100))  // print false
  fmt.Println(isOdd(101))  // print true
  fmt.Println(isEven(100)) // print true
  fmt.Println(isEven(101)) // print false
}

Epilog

Crafting Interpreters is handcrafted by Robert Nystrom.


< Previous - Next >