Created
March 18, 2023 21:07
-
-
Save aaccioly/dea210a8e86c59e68e320d889202a85a to your computer and use it in GitHub Desktop.
Effective Programming in Scala - Week 1 challenge: Generic checkProperty function
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
enum Shape: | |
case Diamond, Squiggle, Oval | |
enum Color: | |
case Red, Green, Purple | |
enum Shading: | |
case Open, Striped, Solid | |
enum NumberType: | |
case One, Two, Three | |
case class Card(shape: Shape, number: NumberType, color: Color, shading: Shading) | |
type PropertyType = Shape | Color | Shading | NumberType | |
enum Property(value: Card => PropertyType): | |
def apply(card: Card): PropertyType = value(card) | |
case Shape extends Property(_.shape) | |
case Color extends Property(_.color) | |
case Shading extends Property(_.shading) | |
case Number extends Property(_.number) | |
def checkProperty(property: Property, card1: Card, card2: Card, card3: Card): Boolean = | |
def allSame = | |
property(card1) == property(card2) && property(card1)== property(card3) | |
def allDifferent = | |
property(card1) != property(card2) && | |
property(card1) != property(card3) && | |
property(card2) != property(card3) | |
allSame || allDifferent | |
def isValidSet(card1: Card, card2: Card, card3: Card): Boolean = | |
Property.values.forall(property => checkProperty(property, card1, card2, card3)) | |
isValidSet( | |
Card(Shape.Diamond, NumberType.One, Color.Purple, Shading.Striped), | |
Card(Shape.Squiggle, NumberType.Two, Color.Purple, Shading.Open), | |
Card(Shape.Oval, NumberType.Three, Color.Purple, Shading.Solid) | |
) | |
isValidSet( | |
Card(Shape.Diamond, NumberType.Two, Color.Purple, Shading.Striped), | |
Card(Shape.Squiggle, NumberType.Two, Color.Purple, Shading.Open), | |
Card(Shape.Oval, NumberType.Three, Color.Purple, Shading.Solid) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment