P
P
Pavel2018-08-23 15:49:57
go
Pavel, 2018-08-23 15:49:57

How to write foldr and foldl in go?

In the exercise task, it was necessary to implement convolution functions . In the description of the assignment, it was written about functional programming, after which I had doubts about the correctness of my decision. Well, i.e. my solution tests pass, but I do it in a loop. Is there any more correct - functional way to solve this problem?

// Fold list from the right
func (l *IntList) Foldr(fn binFunc, init int) (answer int) {
    answer = init
    for i := l.Length() - 1; i >= 0; i— {
        answer = fn((*l)[i], answer)
    }
    return
}
// Fold list from the left
func (l *IntList) Foldl(fn binFunc, init int) (answer int) {
    answer = init
    for i := 0; i < l.Length(); i++ {
        answer = fn(answer, (*l)[i])
    }
    return
}

PS - Just started reading the book Learning Functional Programming in Go

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question