Created
February 10, 2019 13:36
Star
You must be signed in to star a gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scalaz.std.vector.vectorMonoid | |
import scalaz.syntax.foldable.ToFoldableOps | |
import scalaz.syntax.semigroup._ | |
import scalaz.std.list.listInstance | |
// Vector append and prepend functions | |
assert( Vector(1,2) :+ 3 == Vector(1,2,3) ) | |
assert( 1 +: Vector(2,3) == Vector(1,2,3) ) | |
// Vector Monoid zero | |
assert( vectorMonoid[Int].zero == Vector[Int]() ) | |
assert( vectorMonoid[Int].zero == Vector.empty[Int] ) | |
// Vector Monoid associative operation | |
assert( vectorMonoid.append( Vector(1,2), Vector(3,4) ) == Vector(1,2,3,4 )) | |
assert( (Vector(1,2) |+| Vector(3,4)) == Vector(1,2,3,4) ) | |
// turning a list into a vector using Foldable's foldMap and Vector's Monoid | |
assert( List(1,2,3,4,5).foldMap(Vector(_)) == Vector(1,2,3,4,5) ) // specify Monoid implicitly | |
assert( List(1,2,3,4,5).foldMap(Vector(_))(vectorMonoid[Int]) == Vector(1,2,3,4,5) ) // specify Monoid explicitly | |
// doing the same thing but using Foldable's foldRight and foldLeft | |
val zero = vectorMonoid[Int].zero | |
val op = vectorMonoid[Int].append _ | |
assert( List(1,2,3,4,5).foldRight(zero)((n,acc) => op(Vector(n),acc)) == Vector(1,2,3,4,5) ) | |
assert( List(1,2,3,4,5).foldLeft(zero)((acc,n) => op(acc,Vector(n))) == Vector(1,2,3,4,5) ) | |
// doing the same thing but using Vector's append and prepend instead of Vector Monoid's zero and append | |
val append:(Vector[Int],Int) => Vector[Int] = _ :+ _ | |
val prepend:(Int,Vector[Int]) => Vector[Int] = _ +: _ | |
val emptyVector = Vector.empty[Int] | |
assert( List(1,2,3,4,5).foldRight(emptyVector)(prepend) == Vector(1,2,3,4,5) ) | |
assert( List(1,2,3,4,5).foldLeft(emptyVector)(append) == Vector(1,2,3,4,5) ) | |
// Foldable Laws | |
assert( List(1,2,3,4,5).foldMap(Vector(_)) == List(1,2,3,4,5).foldRight(emptyVector)(prepend) ) | |
assert( List(1,2,3,4,5).foldMap(Vector(_)) == List(1,2,3,4,5).foldLeft(emptyVector)(append) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment