scala - Checking on a property of a collection of case-class instances -
consider simple case-class "card" 2 properties ("number" , "color") this:
case class card(number: int, color: string)
consider sequence of cards one:
val cards = seq( card(5, "red"), card(7, "red"), card(3, "black"))
now suppose wanted solve these problems in scala-idiomatic way (functionally oriented?):
- find if cards have same color
- find if cards have same number
- find if cards in ascending order
concretely, have implement these functions:
// cards have same color? def havesamecolor(cards: seq[card], ifempty: boolean = true): boolean = { ??? } // cards have same number? def havesamenumber(cards: seq[card], ifempty: boolean = true): boolean = { ??? } // cards ordered ascendingly? def areascending(cards: seq[card], ifempty: boolean = true): boolean = { ??? }
what possible / best approaches? looping, recursing, folding, reducing?
forall
short-quits met first false
def havesamecolor(cards: seq[card], ifempty: boolean = true) = { if (cards.isempty) ifempty else cards.forall(x => x.color.equals(cards.head.color)) } // not different approach def havesamenumber(cards: seq[card], ifempty: boolean = true): boolean = { if (cards.isempty) ifempty else cards.forall(x => x.number == cards.head.number) } def areascending(cards: seq[card], ifempty: boolean = true): boolean = { if (cards.isempty) ifempty else cards.zip(cards.tail).forall{ case (prev, next) => prev.number <= next.number} }
although, said
is clear default answer should in case of emptiness? not me.
as can see there lot of repetition in function -- clear sign there wrong -- go functions without ifempty parameter.
Comments
Post a Comment