forked from root/public
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
2.5 KiB
2.5 KiB
listforeachif
Instructions
Write a function ListForEachIf
that applies a function given as argument to the information within some nodes of the list.
-
This functions receives two functions:
-
f
is a functions that is applied to the node. -
Comp
is a predicate (a function that returns true or false) and will be use to determine if the functionf
would be applied to the node.
-
-
The function given as argument must have a pointer as argument:
*NodeL
.
Expected function and structure
type NodeL struct {
Data interface{}
Next *NodeL
}
type List struct {
Head *NodeL
Tail *NodeL
}
func IsPositive_node(node *NodeL) bool {
switch node.Data.(type) {
case int, float32, float64, byte:
return node.Data.(int) > 0
case string, rune:
return false
}
return false
}
func IsNegative_node(node *NodeL) bool {
switch node.Data.(type) {
case int, float32, float64, byte:
return node.Data.(int) > 0
case string, rune:
return false
}
return false
}
func IsNotNumeric_node(node *NodeL) bool {
switch node.Data.(type) {
case int, float32, float64, byte:
return false
case string, rune:
return true
}
return true
}
func ListForEachIf(l *List, f func(*NodeL), cond func(*NodeL) bool) {
}
Usage
Here is a possible program to test your function :
package main
import (
piscine ".."
"fmt"
)
func PrintElem(node *piscine.NodeL) {
fmt.Println(node.Data)
}
func StringToInt(node *piscine.NodeL) {
node.Data = 2
}
func PrintList(l *piscine.List) {
it := l.Head
for it != nil {
fmt.Print(it.Data, "->")
it = it.Next
}
fmt.Println()
}
func main() {
link := &piscine.List{}
piscine.ListPushBack(link, 1)
piscine.ListPushBack(link, "hello")
piscine.ListPushBack(link, 3)
piscine.ListPushBack(link, "there")
piscine.ListPushBack(link, 23)
piscine.ListPushBack(link, "!")
piscine.ListPushBack(link, 54)
PrintList(link)
fmt.Println()
fmt.Println("--------function applied--------")
piscine.ListForEachIf(link, PrintElem, piscine.IsPositive_node)
piscine.ListForEachIf(link, StringToInt, piscine.IsNotNumeric_node)
fmt.Println("--------function applied--------")
PrintList(link)
fmt.Println()
}
And its output :
student@ubuntu:~/piscine/test$ go build
student@ubuntu:~/piscine/test$ ./test
1 -> hello -> 3 -> there -> 23 -> ! -> 54 -> <nil>
--------function applied--------
hello
there
!
--------function applied--------
1 -> 1 -> 3 -> 1 -> 23 -> 1 -> 54 -> <nil>
student@ubuntu:~/piscine/test$