Fold Assignment

From CSE425S Wiki
Jump to navigation Jump to search

Lexical scope is not unique to ML. Nearly all programming languages use lexical scope, including Java.

First, we will build the utility methods: foldLeft (which can be easily built with tail recursion) and foldRight (which cannot).

Next, we will build some applications which use fold: sum (which does not require lexical scope) and countBetweenMinAndMaxExclusive (which does).

Code To Implement

Fold

class: FoldHof.java Java.png
methods: foldLeft
foldRight
package: hof.fold.assignment
source folder: src/main/java

SML List Reference

foldLeft

public static <A, B> A foldLeft(BiFunction<A, B, A> f, A acc, ImmutableList<B> list)

foldLeft(f, initial_value, [x1, x2, ..., xn])
returns f(xn,...,f(x2, f(x1, initial_value))...) or initial_value if the list is empty.

foldRight

public static <A, B> A foldRight(BiFunction<A, B, A> f, A acc, ImmutableList<B> list)

foldRight(f, initial_value, [x1, x2, ..., xn])
returns f(x1, f(x2, ..., f(xn, init)...)) or initial_value if the list is empty.

Fold Apps

class: FoldHofApps.java Java.png
methods: sum
countBetweenMinAndMaxExclusive
package: hof.map.assignment
source folder: src/main/java

sum

public static int sum(ImmutableList<Integer> xs)

countBetweenMinAndMaxExclusive

public static int countBetweenMinAndMaxExclusive(int min, int maxExclusive, ImmutableList<Integer> xs)

Test

class: FoldTestSuite.java Junit.png
package: hof.fold.assignment
source folder: src/test/java