Slides for the seventh lesson in my PureScript lunch-n-learn series. This lesson concludes our focus on pattern matching, covering case-of expressions, algebraic data types, and newtypes.
String -> Boolean isPalindrome str = case reverseString str of reversed -> str == reversed _ -> false where reverseString :: String -> String reverseString = toCharArray >>> reverse >>> fromCharArray Use case of to pattern match on the result of a computation
Rectangle Point Number Number | Line Point Point | Text Point String data Point = Point { x :: Number , y :: Number } data keyword for defining an ADT Define a constructor for each possible “shape”
Rectangle Point Number Number | Line Point Point | Text Point String data Point = Point { x :: Number , y :: Number } data keyword for defining an ADT Define a constructor for each possible “shape” Arguments to ADT constructors are not limited to primitive types
Rectangle Point Number Number | Line Point Point | Text Point String data Point = Point { x :: Number , y :: Number } data keyword for defining an ADT Define a constructor for each possible “shape” Arguments to ADT constructors are not limited to primitive types Equally useful for types with a single constructor
Rectangle Point Number Number | Line Point Point | Text Point String data Point = Point { x :: Number , y :: Number } data keyword for defining an ADT Define a constructor for each possible “shape” Arguments to ADT constructors are not limited to primitive types Equally useful for types with a single constructor Constructors may have the same name as the ADT itself
{ x: x, y: y }) = "(" <> show x <> ", " <> show y <> ")" showShape :: Shape -> String showShape (Circle p r) = ... showShape (Rectangle p w h) = ... showShape (Line start end) = ... showShape (Text p text) = ... Nested pattern matching to extract point values Pattern match on each shape
{ x: x, y: y }) = "(" <> show x <> ", " <> show y <> ")" showShape :: Shape -> String showShape (Circle p r) = ... showShape (Rectangle p w h) = ... showShape (Line start end) = ... showShape (Text p text) = ... Nested pattern matching to extract point values Pattern match on each shape Records support same-name destructuring, much like ES6
{ x, y }) = "(" <> show x <> ", " <> show y <> ")" showShape :: Shape -> String showShape (Circle p r) = ... showShape (Rectangle p w h) = ... showShape (Line start end) = ... showShape (Text p text) = ... Nested pattern matching to extract point values Pattern match on each shape Records support same-name destructuring, much like ES6
{ x, y }) = "(" <> show x <> ", " <> show y <> ")" showShape :: Shape -> String showShape (Circle p r) = ... showShape (Rectangle p w h) = ... showShape (Line start end) = ... showShape (Text p text) = ... Nested pattern matching to extract point values Pattern match on each shape Records support same-name destructuring, much like ES6 This works for assignment as well.