Constrained genericity: Difference between revisions

Content added Content deleted
({{omit from|PARI/GP}})
(Go explanation)
Line 209: Line 209:
// an instance of a Banana FoodBox
// an instance of a Banana FoodBox
let someBananas = FoodBox [Banana(); Banana()]</lang>
let someBananas = FoodBox [Banana(); Banana()]</lang>
=={{header|Go}}==
Go's interfaces do exactly what this task wants. Eatable looks like this,
<lang go>type eatable interface {
eat()
}</lang>
And the following is all it takes to define foodbox as a slice of eatables. The result is that an object of type foodbox can hold objects of any type that implements the eat method (with the function signature specified in eatable.) The definition of foodbox though, doesn't even need to enumerate the functions of eatable, much less call them. Whatever is in the interface is okay.
<lang go>type foodbox []eatable</lang>
Here is an example of an eatable type.
<lang go>type peelfirst string

func (f peelfirst) eat() {
// peel code goes here
fmt.Println("mm, that", f, "was good!")
}</lang>
The only thing it takes to make peelfirst eatable is the definition of the eat method. When the eat method is defined, peelfirst automatically becomes an eatable. We say it ''satisfies'' the interface. Notice that "eatable" appears nowhere in the definition of peelfirst or the eat method of peelfirst.

Here is a complete program using these types.
<lang go>package main

import "fmt"

type eatable interface {
eat()
}

type foodbox []eatable

type peelfirst string

func (f peelfirst) eat() {
// peel code goes here
fmt.Println("mm, that", f, "was good!")
}

func main() {
fb := foodbox{peelfirst("banana"), peelfirst("mango")}
f0 := fb[0]
f0.eat()
}</lang>
Output:
<pre>
mm, that banana was good!
</pre>


=={{header|Haskell}}==
=={{header|Haskell}}==