forked from syafdia/go-exercise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedlist.go
94 lines (73 loc) · 1.63 KB
/
linkedlist.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package linkedlist
import (
"fmt"
"github.com/syafdia/go-exercise/src/datastructure/types"
)
type LinkedList interface {
Head() types.T
Tail() LinkedList
Map(mapper func(t types.T) types.U) LinkedList
Filter(filterer func(t types.T) bool) LinkedList
Reduce(initial types.U, reducer func(acc types.U, v types.T) types.U) types.U
String() string
Size() int
}
type node struct {
head types.T
tail LinkedList
}
func New(values ...types.T) LinkedList {
totVals := len(values)
if totVals == 0 {
return node{}
}
head := values[0]
if totVals == 1 {
return node{head: head, tail: nil}
}
return node{head: head, tail: New(values[1:]...)}
}
func (n node) Head() types.T {
return n.head
}
func (n node) Tail() LinkedList {
return n.tail
}
func (n node) Map(mapper func(t types.T) types.U) LinkedList {
if n.tail == nil {
return &node{
head: mapper(n.head),
tail: nil,
}
}
return &node{
head: mapper(n.head),
tail: n.tail.Map(mapper),
}
}
func (n node) Filter(filterer func(t types.T) bool) LinkedList {
if filterer(n.head) {
if n.tail == nil {
return &node{n.head, nil}
}
return &node{n.head, n.tail.Filter(filterer)}
}
if n.tail == nil {
return nil
}
return n.tail.Filter(filterer)
}
func (n node) Reduce(initial types.U, reducer func(acc types.U, v types.T) types.U) types.U {
if n.tail == nil {
return reducer(initial, n.head)
}
return n.tail.Reduce(reducer(initial, n.head), reducer)
}
func (n node) String() string {
return fmt.Sprintf("(%v, %v)", n.head, n.tail)
}
func (n node) Size() int {
return n.Reduce(0, func(acc types.U, _ types.T) types.U {
return acc.(int) + 1
}).(int)
}