BettyES
Posted on November 11, 2018
This is a very short comment about Scala pattern matching.
I recently had to deal with some pattern matching action in Scala. Have you ever been confused by all the match{ case x+> y}
? To fully understand the match-case expressions in scala I tried too use different approaches to solve a simple pattern matching task. Please find the complete code including test suite on github.
The task: Which of Henry's wifes survived? Given a first name and years of marriage (rounded down), one can identify whether Henry's wife died or survived his marriage.
As a reminder:
(1) Catherine of Aragon, 24 years, survived (11 June 1509 – 23 May 1533 ; marriage annulled) ;
(2) Anne Boleyn, 2 years, died (28 May 1533 – 17 May 1536 ; Beheaded 19 May 1536 at the Tower of London. Mother of Elizabeth I);
(3) Jane Seymour,1 year, died (30 May 1536 – 24 October 1537 ; Died 24 October 1537, twelve days after giving birth due to complications. Mother of Edward VI); (4) Anne of Cleves, 0 years, survived (6 January 1540 – 9 July 1540 ; Annulled);
(5) Catherine Howard, 1 year, died (28 July 1540 – 23 November 1541 ; Beheaded 13 February 1542 at the Tower of London),
(6) Catherine Parr, 2 years, survived ( 12 July 1543 – 28 January 1547 ; Widowed ; Survived Henry VIII)
Of course the simplest solution is the following:
(name == "Catherine" && marriage >=2) || (name == "Anne" && marriage <1)
Implementing the match case expression, the following would work as well:
name match {
case "Catherine" => marriage match {
case 1 => false
case _ => true
}
case "Anne" => marriage match {
case 0 => true
case _ => false
}
case _ => false
}
However case also works with an if statement
name match{
case "Catherine" if marriage >= 2 => true
case "Anne" if marriage < 1 => true
case _ => false
}
and finally it is possible to use a boolean
(name == "Catherine" , name =="Anne" , marriage < 1, marriage >=2) match{
case (true, false, false, true) => true
case(false, true, true, false) => true
case(false, false, true, false) => false
case(true,false,true, false) => false
case(false,true, false, true)=> false
case _ => false
}
If anyone can think of any other solutions, I would be keen to see them in the comments section. I am eager to improve my scala coding. =)
Posted on November 11, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.