2 回答
TA贡献1911条经验 获得超7个赞
您必须遵循接口定义,因为它们是为结构定义的,以实现接口。当接口为您的方法定义返回类型时,您必须在实现该接口时返回幺半群。查看以下情况是否有帮助:monoidop
type monoid interface{
get() int
op(monoid, monoid) monoid // mapping_function(monoid,monoid) -> monoid(binary operations in monoid)
ide() monoid // identity_function() -> monoid (return Identity element)
}
func max(a,b int) int{
if a > b{
return a
}else{
return b
}
}
type monoid2 struct{
val int
}
func (m monoid2) get() int {
return m.val
}
func (monoid2) op(x,y monoid) monoid{
return monoid2{max(x.get(),y.get())}
}
func (monoid2) ide() monoid{
return monoid2{-math.MaxInt8}
}
TA贡献1786条经验 获得超11个赞
我成功地定义了幺半群结构。
package main
import (
"fmt"
)
type monoid interface {
get() interface{} // type of interface{} depends on each monoid type.
op(monoid, monoid) monoid // mapping_function(monoid,monoid) -> monoid(binary operations in monoid)
ide() monoid // identity_function() -> monoid (return Identity element)
}
type monoid1 struct {
val int
sum int
}
type monoid2 struct {
name string
power int
}
func (m monoid2) get() interface{} {
return m
}
func (m monoid2) op(x, y monoid) monoid {
a := x.get().(monoid2)
b := y.get().(monoid2)
if len(a.name) > len(b.name) {
return monoid2{a.name, a.power + b.power}
} else {
return monoid2{b.name, a.power + b.power}
}
}
func (m monoid2) ide() monoid {
return monoid2{"", 0}
}
func (m monoid1) get() interface{} {
return m
}
func (m monoid1) op(x, y monoid) monoid {
a := x.get().(monoid1)
b := y.get().(monoid1)
return monoid1{a.val + b.val, a.sum + b.sum}
}
func (m monoid1) ide() monoid {
return monoid1{0, 0}
}
func main() {
a := []monoid{monoid2{"Jame", 100}, monoid2{"Tom", 1010}, monoid2{"BOB SMITH", 1111}, monoid1{1, 1}, monoid1{2, 2}, monoid1{3, 3}}
b := []monoid{monoid2{"Trump", 111}, monoid2{"MaryJames", 1234}, monoid2{"Cachy", 123245}, monoid1{1, 1}, monoid1{2, 2}, monoid1{3, 3}}
for i := 0; i < 6; i++ {
fmt.Println(a[i].op(b[i], a[i]))
}
return
}
- 2 回答
- 0 关注
- 66 浏览
添加回答
举报