pure function on golang

383 views
Skip to first unread message

kurnia...@gmail.com

unread,
Jul 6, 2020, 12:47:27 PM7/6/20
to golang-nuts
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?

Ian Lance Taylor

unread,
Jul 6, 2020, 6:00:21 PM7/6/20
to kurnia...@gmail.com, golang-nuts
On Mon, Jul 6, 2020 at 9:47 AM <kurnia...@gmail.com> wrote:
>
> 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

...

> what do you guys think about this idea?

You didn't really explain what we would gain by adding this to the
language. It's clearly already possible to write pure functions. How
does it help to add the ability to explicitly mark a function as pure?

Ian

bugpowder

unread,
Jul 6, 2020, 6:12:02 PM7/6/20
to golang-nuts
I'd guess the compiler could then enforce it (see if any non-pure marked function is called from a pure one), it could exploit it (e.g. play with evaluation order, cache, etc), and other such things?

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAOyqgcXOdCc8Zz8mXAmghLm%2B6%3Dvi8S8zG_3Phrv2Hy-w%3Dm70kQ%40mail.gmail.com.

Michael Jones

unread,
Jul 6, 2020, 6:14:16 PM7/6/20
to bugpowder, golang-nuts

Ian Lance Taylor

unread,
Jul 6, 2020, 6:56:23 PM7/6/20
to bugpowder, golang-nuts
On Mon, Jul 6, 2020 at 3:11 PM bugpowder <mit...@gmail.com> wrote:
>
> I'd guess the compiler could then enforce it (see if any non-pure marked function is called from a pure one), it could exploit it (e.g. play with evaluation order, cache, etc), and other such things?

The compiler can already tell whether a function is pure, so I don't
think that adding a keyword would lead to any better optimization.

I agree that adding the keyword would let the compiler enforce it, but
that doesn't seem all that big a benefit to me. It also seems like
something that could be done by an analysis tool rather than requiring
a change to the language.

Ian


> On Tue, Jul 7, 2020 at 1:00 AM Ian Lance Taylor <ia...@golang.org> wrote:
>>
>> On Mon, Jul 6, 2020 at 9:47 AM <kurnia...@gmail.com> wrote:
>> >
>> > 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
>>
>> ...
>>
>> > what do you guys think about this idea?
>>
>> You didn't really explain what we would gain by adding this to the
>> language. It's clearly already possible to write pure functions. How
>> does it help to add the ability to explicitly mark a function as pure?
>>
>> Ian
>>
>> --
>> 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...@googlegroups.com.
>> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAOyqgcXOdCc8Zz8mXAmghLm%2B6%3Dvi8S8zG_3Phrv2Hy-w%3Dm70kQ%40mail.gmail.com.
>
> --
> 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...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAACdnTAKTKQxU_K5xRqHGDKKBEhyTAq6%3D6q1HK%2BgDUewgJW1aw%40mail.gmail.com.

Kurniagusta Dwinto

unread,
Jul 6, 2020, 7:52:31 PM7/6/20
to golang-nuts
Adding pure marker will give information to the programmer that the function will not do any side effect, the compiler just gives compile error when the programmer disagrees about the contract, like doing IO operation on pure function.
So in the end, this feature focuses on helping the programmer, not the compiler, to make sure the function does not do any io operation inside it.
I like how Haskell separate IO and non-IO function, they create a clear separation between those worlds,

On the other side, the compiler can evaluate some function in compile-time, although this feature maybe not really needed yet, this will help the programmer to create pre-computed value instead of copying some magic blob data,


> I agree that adding the keyword would let the compiler enforce it, but
> that doesn't seem all that big a benefit to me. It also seems like
> something that could be done by an analysis tool rather than requiring
> a change to the language.

That wouldn't work with interfaces, like

purefunc Hai(x interface{}) int {
  val := 42
  if x, ok := x.(interface { pure Value() int }); ok {
    val += x.Value()
  }
  return val
}

here, without knowing the implementation, the caller of Hai know that Hai will not do any IO operation at all.

I've tried to create an analysis tool to do that before. I need to mark the pure function with "Pure" suffix, 
the code above will be

func HaiPure(x interface{}) int {
  val := 42
  if x, ok := x.(interface { ValuePure() int }); ok {
    val += x.ValuePure()
  }
  return val
}

But when it comes to passing a function as a parameter, it will become more subtle

purefunc Hai(x purefunc() int) int {
  return 42 + x()
}

// this should generate a compile error
a := 20
fmt.Println(Hai(purefunc() int {
  a += 1 // side effect
  fmt.Println("something") // side effect
  return a
}))

Kurniagusta Dwinto

unread,
Jul 6, 2020, 8:04:38 PM7/6/20
to golang-nuts
Additionally, this feature complement new generic feature,
this feature will help anyone that trying to use functional programming pattern (like monad pattern) in their code

Ian Lance Taylor

unread,
Jul 6, 2020, 8:05:43 PM7/6/20
to Kurniagusta Dwinto, golang-nuts
Fair point about interfaces.

There are many many different attributes we could apply to functions
in Go. For example, one that is commonly requested is "this
function/method does not modify memory via this pointer," which in C
or C++ is implemented using the "const" type qualifier. It's not
obvious to me that "pure" is a characteristic that is important enough
to be singled out and added to the language. I suppose it might be
useful in some cases, but the test for whether something is worth
adding to the language is whether the benefit is worth the cost.

Ian

Kurniagusta Dwinto

unread,
Jul 6, 2020, 8:12:00 PM7/6/20
to golang-nuts
> It's not obvious to me that "pure" is a characteristic that is important enough
> to be singled out and added to the language

the name "pure" may be debatable, but the characteristic is the same with "constexpr" in C++, although I also don't have a strong reason why this is important beside separation IO and non-IO

You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/RfruW8qemOg/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/c75305e2-27e4-4a33-9111-d5b1c54eb9c9n%40googlegroups.com.


--
Regards,
Kurniagusta Dwinto
Fakultas Ilmu Komputer, Universitas Indonesia

Michael Jones

unread,
Jul 6, 2020, 8:18:37 PM7/6/20
to Kurniagusta Dwinto, golang-nuts
i would value "pure" if it were a contract for early evaluation. in my post on this from 2018 (linked above), the reasoning was so that "x := math.Sin(0.23)" would be a compile-time event.

Ian Lance Taylor

unread,
Jul 6, 2020, 8:34:14 PM7/6/20
to Kurniagusta Dwinto, golang-nuts
On Mon, Jul 6, 2020 at 5:11 PM Kurniagusta Dwinto
<kurnia...@gmail.com> wrote:
>
> > It's not obvious to me that "pure" is a characteristic that is important enough
> > to be singled out and added to the language
>
> the name "pure" may be debatable, but the characteristic is the same with "constexpr" in C++, although I also don't have a strong reason why this is important beside separation IO and non-IO

Well, C++ is a very different language with very different goals. I
think history shows that C++ is much more comfortable adding new
features than Go is.
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAEz1khoDwcKXdieicdSgXGQ8ruwKw4m3FCh8sSkTVoOcOqb2SA%40mail.gmail.com.

Kurniagusta Dwinto

unread,
Jul 6, 2020, 8:46:48 PM7/6/20
to golang-nuts
> i would value "pure" if it were a contract for early evaluation
does this "early evaluation" concern about IO? like loading blob data with ioutil.ReadFile into global variable at compile time?


> Well, C++ is a very different language with very different goals. I
> think history shows that C++ is much more comfortable adding new
> features than Go is.
Yeah, true, and I'm okay with that.
me alone maybe not enough to justify it, I created this post here to see if others also need this feature and justify the cost to add it to the language.

Brian Candler

unread,
Jul 7, 2020, 7:43:14 AM7/7/20
to golang-nuts
On Tuesday, 7 July 2020 01:46:48 UTC+1, Kurniagusta Dwinto wrote:
> i would value "pure" if it were a contract for early evaluation
does this "early evaluation" concern about IO? like loading blob data with ioutil.ReadFile into global variable at compile time?

I think by definition, any function which accesses the filesystem is not pure, since it depends on external state (the state of the filesystem).

Michael Jones

unread,
Jul 7, 2020, 9:32:02 AM7/7/20
to Brian Candler, golang-nuts
The standard math library is a natural, easy gateway; a simple preprocessor could do it. maybe i'll prototype  it.

--
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...@googlegroups.com.

Haddock

unread,
Jul 7, 2020, 12:58:20 PM7/7/20
to golang-nuts
> the name "pure" may be debatable, but the characteristic is the same with "constexpr" in C++, although I also don't have a strong reason why this is important beside separation IO and non-IO

D is a lange that has true pure functions, see https://dlang.org/spec/function.html#pure-functions

While D is a very feature rich and elaborate language Go is made with simplicity as the driving design criteria in mind. If you want very elaborate things like pure functions Go might be the wrong language choice as in Go things will continue to strive for simplicity.

Jesper Louis Andersen

unread,
Jul 8, 2020, 4:37:07 AM7/8/20
to kurnia...@gmail.com, golang-nuts
On Mon, Jul 6, 2020 at 6:46 PM <kurnia...@gmail.com> wrote:

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)


You also need an additional property, namely that the function always returns the same output for a given input. That is, it is a "stable" relation from inputs to outputs. Consider e.g.


where we read a global variable as part of the function body. You could make this into an escaping variable in a closure if you want something more local, but the global will serve the same purpose. There are many variants of this scheme, for instance by reading on a channel as part of the function body, and having that channel fed random values, etc.

Marking an expression as pure is a nominal type of language construction. Go usually prefers structural language constructions in most places, so I don't think it fits into the language design as a whole.

Kurniagusta Dwinto

unread,
Jul 13, 2020, 12:13:40 PM7/13/20
to golang-nuts
Hello guys, thanks for the response, 
After brainstorming for a while, I think we can implement this without changes in the language, and create static analysis tools for it,
What's wrong with my approach before is using the suffix "Pure" as a pure function marker, which is unreliable because the function name is not part of the function signature.
So to mark a function is pure, we need to embed the pure marker into the function signature, so it's impossible to lose this information,
then, the next observation is pure function must return something, there is no point of having a pure function that returns nothing.
With these facts and generic feature in the next golang, We can create a new type in a new package

// pure.go
package pure
type Value (type T) struct { Value T }

then to mark a function pure, we can use it like this:

func Sum(data []int) pure.Value(int) {

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

the rest is the job for a static analysis tool to analyze that the purity contract is hold

This will also solve my problem about using a pure function in interface type as I state above
Reply all
Reply to author
Forward
0 new messages