More on Fold

This is a followup post to: Functional Swift: Fold it, baby!

The Accumulator Value

A small tip I forgot to mention about the initial accumulator value. Often times you can think of it as the neutral element of the operation you pass to fold. For example in the sum function the operation is addition. To not affect the final solution by the initial accumulator you use the neutral element to addition, which is zero.

More Variants of Fold

Speaking of the initial accumulator value, there is a version of fold that uses the first element of the list as its initial accumulator called foldl1. And these two versions of fold can be reversed so that the list is processed from right to left, foldr and foldr1.

foldl1

Like foldl but with the first element as the starting accumulator.

func foldl1<A>(list: Array<A>, f: (A
Read More...

Functional Swift: Fold it, baby!

Introduction

Pure functional languages don't have the notion of mutable values and therefore don't have any variable assignment. You only have values and expressions, you can give them names, but you can't change the underlying value for a name.

// you get this behaviour in swift, when using let
let n = 42  
n = 7 // immutable value, reassignment is not allowed  

At first this can be cumbersome, because you can't use many familiar structures that you are used to in imperative languages. One of these structures are loops. Think about a for-loop, you need to increment or decrement a control variable to jump out of the loop at one time. Or take a while-loop, you have to change some state so that the boolean expression evaluates to false and you jump out of the while-loop.

But to implement every computable algorithm you need a form of iteration in the language. So how

Read More...