Created
January 17, 2017 19:34
-
-
Save exallium/a982a6ca9f7e14f64705cbef6dd3a1bd to your computer and use it in GitHub Desktop.
Simple Monoid Verifier
This file contains hidden or 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
// Our Monoid interface, which provides an "append" and "empty" | |
interface Monoid<M> { | |
fun append(l: M, r: M): M | |
fun empty(): M | |
} | |
sealed class ValidationResult { | |
companion object : Monoid<ValidationResult> { | |
// Appends two validation results. If both are failures, append messages with newline | |
// otherwise, emit a failure with message if one exists | |
// otherwise, emit success | |
override fun append(l: ValidationResult, r: ValidationResult): ValidationResult { | |
val failures = listOf(l, r).filter { it is Failure }.map { it as Failure } | |
if (failures.size == 0) { | |
return empty() | |
} else { | |
return Failure(failures.map { it.msg }.reduce {a, b -> a + "\n" + b }) | |
} | |
} | |
// We are "successful" by default | |
override fun empty() = Success() | |
} | |
class Success : ValidationResult() { | |
override fun toString() = "Success" | |
} | |
class Failure(val msg: String): ValidationResult() { | |
override fun toString() = "Failure $msg" | |
} | |
} | |
fun <M> reduce(m: Monoid<M>, ms: List<M>) = ms.reduce { a, b -> m.append(a, b) } | |
fun myValidation(str: String): ValidationResult { | |
return if (str.length > 5) { | |
ValidationResult.Success() | |
} else { | |
ValidationResult.Failure("string too short") | |
} | |
} | |
fun main(args: Array<String>) { | |
val strings = listOf("hello", "world", "I", "am", "going", "to", "reduce") | |
val results = strings.map { myValidation(it) } | |
val reduction = reduce(ValidationResult, results) | |
println(reduction) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment