Hi, I don't know if this kind of idea is already discussed before.

I have an idea of adding pure function marker/type on golang, it is just 
like "constexpr" on C++ or "const fn" on Rust, whether this function is 
evaluated at compile time if the input is known at compile time is another 
discussion,
I don't think this idea is hard to implement

to my understanding, a pure function is a function that doesn't have a side 
effect, so we can limit pure function to:
- unable to call non-pure function
- unable to modify a variable that is not declared on current function 
(like a global variable)

for this purpose, we can think receiver as input to the function

for example:

normal pure function
purefunc Sum(data []int) int {
  // any modification to data is compile error, like
  // data[0] = 20

  // or call to non pure function is also compile error
  // data = append(data, 12)

  total := 0
  for _, x := range data {
    total += x
  }
  return total
}

pure function with a receiver
type mylist struct {
  data []int
}

func (l *mylist) print() {
  fmt.Println(l.data)
}

purefunc (l *mylist) print2() {
  // this will compile error, because fmt.Println is not purefunc
  // fmt.Println(l.data)
}

purefunc (l *mylist) sum() int {
  // updating l will compile error, like
  // l.data[0] = 12
  // l.data = []int{1, 2, 3}

  // calling to non-pure function also compile error
  // l.print()

  total := 0
  for _, x := range l.data {
    total += x
  }
  return total
}

accepting and returning pure function
func lala(f purefunc() int) {
  fmt.Println(f())
}

func doLala() {
  x := &mylist{data: []int{1, 2, 3}}
  lala(x.sum)
}

purefunc createAdder(x int) purefunc(int) int {
  return purefunc(y int) int {
    // updating x here will compile error, because x is not declared in 
this function
    // x += 1
    return x + y
  }
}

func doCreateAdder() {
  var addFive purefunc(int) int = createAdder(5)

  // pure function is convertible to non pure function
  var addFive2 func(int) int = addFive

  fmt.Println(addFive(5))
  fmt.Println(addFive2(10))
}


interaction pure function with interface (we need to add keyword "pure" in 
function list)
type myStruct struct {}

func (myStruct) xxxx() {}
purefunc (myStruct) yyyy() {}

func lala() {
  a := myStruct{}

  // this compile error, non-pure function is not convertible to pure one
  // var x interface { pure xxxx() } = a

  // but pure function is convertible to non-pure function
  var x interface { yyyy() } = a
}


what do you guys think about this idea?

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/36fbf41b-0a69-4852-a9e3-09dc65edddc7o%40googlegroups.com.

Reply via email to