Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Initial encoded email filter example
object initial_encoded_email_filter {
final case class Address(emailAddress: String)
final case class Email(sender: Address, to: List[Address], subject: String, body: String)
sealed trait EmailFilter { self =>
def &&(that: EmailFilter): EmailFilter = EmailFilter.And(self, that)
def ||(that: EmailFilter): EmailFilter = (self.negate && that.negate).negate
def negate : EmailFilter = EmailFilter.Not(self)
import EmailFilter._
def run(email: Email): Boolean = self match {
case Always => true
case Not(filter: EmailFilter) => !
case And(left: EmailFilter, right: EmailFilter) => &&
case SenderEquals(target: Address) => target == email.sender
case RecipientEquals(target: Address) =>
case BodyContains(phrase: String) => email.body.contains(phrase)
object EmailFilter {
final case object Always extends EmailFilter
final case class Not(filter: EmailFilter) extends EmailFilter
final case class And(left: EmailFilter, right: EmailFilter) extends EmailFilter
final case class SenderEquals(target: Address) extends EmailFilter
final case class RecipientEquals(target: Address) extends EmailFilter
final case class BodyContains(phrase: String) extends EmailFilter
val always: EmailFilter = Always
val never: EmailFilter = always.negate
def senderIs(sender: Address): EmailFilter = SenderEquals(sender)
def senderIsNot(sender: Address): EmailFilter = SenderEquals(sender).negate
def recipientIs(recipient: Address): EmailFilter = RecipientEquals(recipient)
def recipientIsNot(recipient: Address): EmailFilter = RecipientEquals(recipient).negate
def senderIn(senders: Set[Address]): EmailFilter = senders.foldLeft(never)(_ || senderIs(_))
def recipientIn(recipients: Set[Address]): EmailFilter = recipients.foldLeft(never)(_ || recipientIs(_))
def bodyContains(phrase: String): EmailFilter = BodyContains(phrase)
def bodyDoesNotContain(phrase: String): EmailFilter = BodyContains(phrase).negate
val filter: EmailFilter = EmailFilter.senderIsNot(Address("")) && EmailFilter.bodyContains("Unsubscribe")
val emails: List[Email] = List(Email(Address(""), List(Address("")), "Promotion", "10% off. Unsubscribe"))
val newsletters: List[Email] = emails.filter(
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment