|
|
|
## listforeach
|
|
|
|
|
|
|
|
### Instructions
|
|
|
|
|
|
|
|
Write a function `ListForEach` that applies a function given as argument to the data within each node of the list `l`.
|
|
|
|
|
|
|
|
- The function given as argument must have a pointer as argument: `l *List`
|
|
|
|
|
|
|
|
- Copy the functions `Add2_node` and `Subtract3_node` in the same file as the function `ListForEach` is defined.
|
|
|
|
|
|
|
|
### Expected function and structure
|
|
|
|
|
|
|
|
```go
|
|
|
|
type NodeL struct {
|
|
|
|
Data interface{}
|
|
|
|
Next *NodeL
|
|
|
|
}
|
|
|
|
|
|
|
|
type List struct {
|
|
|
|
Head *NodeL
|
|
|
|
Tail *NodeL
|
|
|
|
}
|
|
|
|
|
|
|
|
func ListForEach(l *List, f func(*NodeL)) {
|
|
|
|
}
|
|
|
|
|
|
|
|
func Add2_node(node *NodeL) {
|
|
|
|
switch node.Data.(type) {
|
|
|
|
case int:
|
|
|
|
node.Data = node.Data.(int) + 2
|
|
|
|
case string:
|
|
|
|
node.Data = node.Data.(string) + "2"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func Subtract3_node(node *NodeL) {
|
|
|
|
switch node.Data.(type) {
|
|
|
|
case int:
|
|
|
|
node.Data = node.Data.(int) - 3
|
|
|
|
case string:
|
|
|
|
node.Data = node.Data.(string) + "-3"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
### Usage
|
|
|
|
|
|
|
|
Here is a possible program to test your function :
|
|
|
|
|
|
|
|
```go
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"piscine"
|
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
link := &piscine.List{}
|
|
|
|
|
|
|
|
piscine.ListPushBack(link, "1")
|
|
|
|
piscine.ListPushBack(link, "2")
|
|
|
|
piscine.ListPushBack(link, "3")
|
|
|
|
piscine.ListPushBack(link, "5")
|
|
|
|
|
|
|
|
piscine.ListForEach(link, piscine.Add2_node)
|
|
|
|
|
|
|
|
it := link.Head
|
|
|
|
for it != nil {
|
|
|
|
fmt.Println(it.Data)
|
|
|
|
it = it.Next
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
And its output :
|
|
|
|
|
|
|
|
```console
|
|
|
|
$ go run .
|
|
|
|
12
|
|
|
|
22
|
|
|
|
32
|
|
|
|
52
|
|
|
|
$
|
|
|
|
```
|