text: (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[44192],{17375:function(e,t,n){"use strict";function a(e,t){if(null==e)return{};var n,a,r=function(e,t){if(null==e)return{};var n,a,r={},s=Object.keys(e);for(a=0;a<s.length;a++)n=s[a],t.indexOf(n)>=0||(r[n]=e[n]);return r}(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(a=0;a<s.length;a++)n=s[a],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}n.d(t,{Z:function(){return a}})},92304:function(e,t,n){"use strict";n.r(t),n.d(t,{default:function(){return c}});var a=n(17375),r=n(96156),s=(n(67294),n(3905));function l(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);t&&(a=a.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,a)}return n}function o(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?l(Object(n),!0).forEach((function(t){(0,r.Z)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):l(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var i,p=(i="CodeTab",function(e){return console.warn("Component "+i+" was not imported, exported, or provided by MDXProvider as global scope"),(0,s.kt)("div",o({},e))}),u={};function c(e){var t=e.components,n=(0,a.Z)(e,["components"]);return(0,s.kt)("wrapper",o(o(o({},u),n),{},{components:t,mdxType:"MDXLayout"}),(0,s.kt)("h1",o({},{id:"pattern-matching--destructuring"}),"Pattern Matching / Destructuring"),(0,s.kt)("p",null,"One of ReScript's ",(0,s.kt)("strong",{parentName:"p"},"best")," feature is our pattern matching. Pattern matching combines 3 brilliant features into one:"),(0,s.kt)("ul",null,(0,s.kt)("li",{parentName:"ul"},"Destructuring."),(0,s.kt)("li",{parentName:"ul"},(0,s.kt)("inlineCode",{parentName:"li"},"switch")," based on shape of data."),(0,s.kt)("li",{parentName:"ul"},"Exhaustiveness check.")),(0,s.kt)("p",null,"We'll dive into each aspect below."),(0,s.kt)("h2",o({},{id:"destructuring"}),"Destructuring"),(0,s.kt)("p",null,'Even JavaScript has destructuring, which is "opening up" a data structure to extract the parts we want and assign variable names to them:'),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),"let coordinates = (10, 20, 30)\nlet (x, _, _) = coordinates\nJs.log(x) // 10\n")),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),"var coordinates = [10, 20, 30];\nvar x = 10;\nconsole.log(10);\n"))),(0,s.kt)("p",null,"Destructuring works with most built-in data structures:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res"}),'// Record\ntype student = {name: string, age: int}\nlet student1 = {name: "John", age: 10}\nlet {name} = student1 // "John" assigned to `name`\n\n// Variant\ntype result =\n  | Success(string)\nlet myResult = Success("You did it!")\nlet Success(message) = myResult // "You did it!" assigned to `message`\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'var student1 = {\n  name: "John",\n  age: 10\n};\nvar name = "John";\n\nvar myResult = /* Success */{\n  _0: "You did it!"\n};\nvar message = "You did it!"\n\nvar myArray = [1, 2, 3];\nif (myArray.length !== 2) {\n  throw {\n    RE_EXN_ID: "Match_failure",\n    _1: [\n      "playground.res",\n      14,\n      4\n    ],\n    Error: new Error()\n  };\n}\nvar item1 = myArray[0];\nvar item2 = myArray[1];\n\nvar myList = {\n  hd: 1,\n  tl: {\n    hd: 2,\n    tl: {\n      hd: 3,\n      tl: /* [] */0\n    }\n  }\n};\n// ...\n'))),(0,s.kt)("p",null,"You can also use destructuring anywhere you'd usually put a binding:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),'type result =\n  | Success(string)\nlet displayMessage = (Success(m)) => {\n  // we\'ve directly extracted the success message\n  // string by destructuring the parameter\n  Js.log(m)\n}\ndisplayMessage(Success("You did it!"))\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'function displayMessage(m) {\n  console.log(m._0);\n}\n\ndisplayMessage(/* Success */{\n  _0: "You did it!"\n});\n'))),(0,s.kt)("p",null,"For a record, you can rename the field while destructuring:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res"}),'let {name: n} = student1 // "John" assigned to `n`\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'var n = "John";\n'))),(0,s.kt)("p",null,"You ",(0,s.kt)("em",{parentName:"p"},"can")," in theory destructure array and list at the top level too:"),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res"}),"let myArray = [1, 2, 3]\nlet [item1, item2, _] = myArray\n// 1 assigned to `item1`, 2 assigned to `item2`, 3rd item ignored\n\nlet myList = list{1, 2, 3}\nlet list{head, ...tail} = myList\n// 1 assigned to `head`, `list{2, 3}` assigned to tail\n")),(0,s.kt)("p",null,"But the array example is ",(0,s.kt)("strong",{parentName:"p"},"highly disrecommended")," (use tuple instead) and the list example will error on you. They're only there for completeness' sake. As you'll see below, the proper way of using destructuring array and list is using ",(0,s.kt)("inlineCode",{parentName:"p"},"switch"),"."),(0,s.kt)("h2",o({},{id:"switch-based-on-shape-of-data"}),(0,s.kt)("inlineCode",{parentName:"h2"},"switch")," Based on Shape of Data"),(0,s.kt)("p",null,"While the destructuring aspect of pattern matching is nice, it doesn't really change the way you think about structuring your code. One paradigm-changing way of thinking about your code is to execute some code based on the shape of the data."),(0,s.kt)("p",null,"Consider a variant:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"prelude",prelude:!0}),"type payload =\n  | BadResult(int)\n  | GoodResult(string)\n  | NoResult\n")),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),"// Empty output\n"))),(0,s.kt)("p",null,"We'd like to handle each of the 3 cases differently. For example, print a success message if the value is ",(0,s.kt)("inlineCode",{parentName:"p"},"GoodResult(...)"),", do something else when the value is ",(0,s.kt)("inlineCode",{parentName:"p"},"NoResult"),", etc."),(0,s.kt)("p",null,"In other languages, you'd end up with a series of if-elses that are hard to read and error-prone. In ReScript, you can instead use the supercharged ",(0,s.kt)("inlineCode",{parentName:"p"},"switch")," pattern matching facility to destructure the value while calling the right code based on what you destructured:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),'let data = GoodResult("Product shipped!")\nswitch data {\n| GoodResult(theMessage) =>\n  Js.log("Success! " ++ theMessage)\n| BadResult(errorCode) =>\n  Js.log("Something\'s wrong. The error code is: " ++ Js.Int.toString(errorCode))\n| NoResult =>\n  Js.log("Bah.")\n}\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'var data = {\n  TAG: /* GoodResult */1,\n  _0: "Product shipped!"\n};\n\nif (typeof data === "number") {\n  console.log("Bah.");\n} else if (data.TAG === /* BadResult */ 0) {\n  console.log("Something\'s wrong. The error code is: " + "Product shipped!".toString());\n} else {\n  console.log("Success! Product shipped!");\n}\n'))),(0,s.kt)("p",null,"In this case, ",(0,s.kt)("inlineCode",{parentName:"p"},"message")," will have the value ",(0,s.kt)("inlineCode",{parentName:"p"},'"Success! Product shipped!"'),"."),(0,s.kt)("p",null,"Suddenly, your if-elses that messily checks some structure of the value got turned into a clean, compiler-verified, linear list of code to execute based on exactly the shape of the value."),(0,s.kt)("h3",o({},{id:"complex-examples"}),"Complex Examples"),(0,s.kt)("p",null,"Here's a real-world scenario that'd be a headache to code in other languages. Given this data structure:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"prelude",prelude:!0}),"type status = Vacations(int) | Sabbatical(int) | Sick | Present\ntype reportCard = {passing: bool, gpa: float}\ntype person =\n  | Teacher({\n    name: string,\n    age: int,\n  })\n  | Student({\n    name: string,\n    status: status,\n    reportCard: reportCard,\n  })\n")),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),"// Empty output\n"))),(0,s.kt)("p",null,"Imagine this requirement:"),(0,s.kt)("ul",null,(0,s.kt)("li",{parentName:"ul"},"Informally greet a person who's a teacher and if his name is Mary or Joe."),(0,s.kt)("li",{parentName:"ul"},"Greet other teachers formally."),(0,s.kt)("li",{parentName:"ul"},"If the person's a student, congratulate him/her score if they passed the semester."),(0,s.kt)("li",{parentName:"ul"},"If the student has a gpa of 0 and is on vacations or sabbatical, display a different message."),(0,s.kt)("li",{parentName:"ul"},"A catch-all message for a student.")),(0,s.kt)("p",null,"ReScript can do this easily!"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"prelude",prelude:!0}),'let person1 = Teacher({name: "Jane", age: 35})\n\nlet message = switch person1 {\n| Teacher({name: "Mary" | "Joe"}) =>\n  `Hey, still going to the party on Saturday?`\n| Teacher({name}) =>\n  // this is matched only if `name` isn\'t "Mary" or "Joe"\n  `Hello ${name}.`\n| Student({name, reportCard: {passing: true, gpa}}) =>\n  `Congrats ${name}, nice GPA of ${Js.Float.toString(gpa)} you got there!`\n| Student({\n    reportCard: {gpa: 0.0},\n    status: Vacations(daysLeft) | Sabbatical(daysLeft)\n  }) =>\n  `Come back in ${Js.Int.toString(daysLeft)} days!`\n| Student({status: Sick}) =>\n  `How are you feeling?`\n| Student({name}) =>\n  `Good luck next semester ${name}!`\n}\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'var person1 = {\n  TAG: /* Teacher */0,\n  name: "Jane",\n  age: 35\n};\n\nvar message;\n\nif (person1.TAG) {\n  var match$1 = person1.status;\n  var name = person1.name;\n  var match$2 = person1.reportCard;\n  message = match$2.passing\n    ? "Congrats " +\n      name +\n      ", nice GPA of " +\n      match$2.gpa.toString() +\n      " you got there!"\n    : typeof match$1 === "number"\n    ? match$1 !== 0\n      ? "Good luck next semester " + name + "!"\n      : "How are you feeling?"\n    : person1.reportCard.gpa !== 0.0\n    ? "Good luck next semester " + name + "!"\n    : "Come back in " + match$1._0.toString() + " days!";\n} else {\n  var name$1 = person1.name;\n  switch (name$1) {\n    case "Joe":\n    case "Mary":\n      message = "Hey, still going to the party on Saturday?";\n      break;\n    default:\n      message = "Hello " + name$1 + ".";\n  }\n}\n'))),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Note")," how we've:"),(0,s.kt)("ul",null,(0,s.kt)("li",{parentName:"ul"},"drilled deep down into the value concisely"),(0,s.kt)("li",{parentName:"ul"},"using a ",(0,s.kt)("strong",{parentName:"li"},"nested pattern check")," ",(0,s.kt)("inlineCode",{parentName:"li"},'"Mary" | "Joe"')," and ",(0,s.kt)("inlineCode",{parentName:"li"},"Vacations | Sabbatical")),(0,s.kt)("li",{parentName:"ul"},"while extracting the ",(0,s.kt)("inlineCode",{parentName:"li"},"daysLeft")," number from the latter case"),(0,s.kt)("li",{parentName:"ul"},"and assigned the greeting to the binding ",(0,s.kt)("inlineCode",{parentName:"li"},"message"),".")),(0,s.kt)("p",null,"Here's another example of pattern matching, this time on an inline tuple."),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res"}),"type animal = Dog | Cat | Bird\nlet categoryId = switch (isBig, myAnimal) {\n| (true, Dog) => 1\n| (true, Cat) => 2\n| (true, Bird) => 3\n| (false, Dog | Cat) => 4\n| (false, Bird) => 5\n}\n")),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),"var categoryId = isBig ? (myAnimal + 1) | 0 : myAnimal >= 2 ? 5 : 4;\n"))),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Note")," how pattern matching on a tuple is equivalent to a 2D table:"),(0,s.kt)("table",null,(0,s.kt)("thead",{parentName:"table"},(0,s.kt)("tr",{parentName:"thead"},(0,s.kt)("th",o({parentName:"tr"},{align:null}),"isBig \\ myAnimal"),(0,s.kt)("th",o({parentName:"tr"},{align:null}),"Dog"),(0,s.kt)("th",o({parentName:"tr"},{align:null}),"Cat"),(0,s.kt)("th",o({parentName:"tr"},{align:null}),"Bird"))),(0,s.kt)("tbody",{parentName:"table"},(0,s.kt)("tr",{parentName:"tbody"},(0,s.kt)("td",o({parentName:"tr"},{align:null}),"true"),(0,s.kt)("td",o({parentName:"tr"},{align:null}),"1"),(0,s.kt)("td",o({parentName:"tr"},{align:null}),"2"),(0,s.kt)("td",o({parentName:"tr"},{align:null}),"3")),(0,s.kt)("tr",{parentName:"tbody"},(0,s.kt)("td",o({parentName:"tr"},{align:null}),"false"),(0,s.kt)("td",o({parentName:"tr"},{align:null}),"4"),(0,s.kt)("td",o({parentName:"tr"},{align:null}),"4"),(0,s.kt)("td",o({parentName:"tr"},{align:null}),"5")))),(0,s.kt)("h3",o({},{id:"fall-through-patterns"}),"Fall-Through Patterns"),(0,s.kt)("p",null,"The nested pattern check, demonstrated in the earlier ",(0,s.kt)("inlineCode",{parentName:"p"},"person")," example, also works at the top level of a ",(0,s.kt)("inlineCode",{parentName:"p"},"switch"),":"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"prelude",prelude:!0}),'let myStatus = Vacations(10)\n\nswitch myStatus {\n| Vacations(days)\n| Sabbatical(days) => Js.log(`Come back in ${Js.Int.toString(days)} days!`)\n| Sick\n| Present => Js.log("Hey! How are you?")\n}\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'var myStatus = {\n  TAG: /* Vacations */0,\n  _0: 10\n};\n\nif (typeof myStatus === "number") {\n  console.log("Hey! How are you?");\n} else {\n  console.log("Come back in " + (10).toString() + " days!");\n}\n'))),(0,s.kt)("p",null,"Having multiple cases fall into the same handling can clean up certain types of logic."),(0,s.kt)("h3",o({},{id:"ignore-part-of-a-value"}),"Ignore Part of a Value"),(0,s.kt)("p",null,"If you have a value like ",(0,s.kt)("inlineCode",{parentName:"p"},"Teacher(payload)")," where you just want to pattern match on the ",(0,s.kt)("inlineCode",{parentName:"p"},"Teacher")," part and ignore the ",(0,s.kt)("inlineCode",{parentName:"p"},"payload")," completely, you can use the ",(0,s.kt)("inlineCode",{parentName:"p"},"_")," wildcard like this:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),'switch person1 {\n| Teacher(_) => Js.log("Hi teacher")\n| Student(_) => Js.log("Hey student")\n}\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'if (person1.TAG) {\n  console.log("Hey student");\n} else {\n  console.log("Hi teacher");\n}\n'))),(0,s.kt)("p",null,(0,s.kt)("inlineCode",{parentName:"p"},"_")," also works at the top level of the ",(0,s.kt)("inlineCode",{parentName:"p"},"switch"),", serving as a catch-all condition:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),'switch myStatus {\n| Vacations(_) => Js.log("Have fun!")\n| _ => Js.log("Ok.")\n}\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'if (typeof myStatus === "number" || myStatus.TAG) {\n  console.log("Ok.");\n} else {\n  console.log("Have fun!");\n}\n'))),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Do not")," abuse a top-level catch-all condition. Instead, prefer writing out all the cases:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),'switch myStatus {\n| Vacations(_) => Js.log("Have fun!")\n| Sabbatical(_) | Sick | Present => Js.log("Ok.")\n}\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'if (typeof myStatus === "number" || myStatus.TAG) {\n  console.log("Ok.");\n} else {\n  console.log("Have fun!");\n}\n'))),(0,s.kt)("p",null,"Slightly more verbose, but a one-time writing effort. This helps when you add a new variant case e.g. ",(0,s.kt)("inlineCode",{parentName:"p"},"Quarantined")," to the ",(0,s.kt)("inlineCode",{parentName:"p"},"status")," type and need to update the places that pattern match on it. A top-level wildcard here would have accidentally and silently continued working, potentially causing bugs."),(0,s.kt)("h3",o({},{id:"if-clause"}),"If Clause"),(0,s.kt)("p",null,"Sometime, you want to check more than the shape of a value. You want to also run some arbitrary check on it. You might be tempted to write this:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),'switch person1 {\n| Teacher(_) => () // do nothing\n| Student({reportCard: {gpa}}) =>\n  if gpa < 0.5 {\n    Js.log("What\'s happening")\n  } else {\n    Js.log("Heyo")\n  }\n}\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'if (person1.TAG) {\n  if (person1.reportCard.gpa < 0.5) {\n    console.log("What\'s happening");\n  } else {\n    console.log("Heyo");\n  }\n}\n'))),(0,s.kt)("p",null,(0,s.kt)("inlineCode",{parentName:"p"},"switch")," patterns support a shortcut for the arbitrary ",(0,s.kt)("inlineCode",{parentName:"p"},"if")," check, to keep your pattern linear-looking:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),'switch person1 {\n| Teacher(_) => () // do nothing\n| Student({reportCard: {gpa}}) if gpa < 0.5 =>\n  Js.log("What\'s happening")\n| Student(_) =>\n  // fall-through, catch-all case\n  Js.log("Heyo")\n}\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'if (person1.TAG) {\n  if (person1.reportCard.gpa < 0.5) {\n    console.log("What\'s happening");\n  } else {\n    console.log("Heyo");\n  }\n}\n'))),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Note:")," In ReScript version < 9.0, the ",(0,s.kt)("inlineCode",{parentName:"p"},"if")," clause is denoted as a ",(0,s.kt)("inlineCode",{parentName:"p"},"when"),", but will be reformatted to ",(0,s.kt)("inlineCode",{parentName:"p"},"if")," in newer versions."),(0,s.kt)("h3",o({},{id:"match-on-exceptions"}),"Match on Exceptions"),(0,s.kt)("p",null,"If the function throws an exception (covered later), you can also match on ",(0,s.kt)("em",{parentName:"p"},"that"),", in addition to the function's normally returned values."),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res"}),'switch List.find(i => i === theItem, myItems) {\n| item => Js.log(item)\n| exception Not_found => Js.log("No such item found!")\n}\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'var exit = 0;\n\nvar item;\n\ntry {\n  item = List.find(function(i) {\n    return i === theItem;\n  }, myItems);\n  exit = 1;\n}\ncatch (raw_exn){\n  var exn = Caml_js_exceptions.internalToOCamlException(raw_exn);\n  if (exn.RE_EXN_ID === "Not_found") {\n    console.log("No such item found!");\n  } else {\n    throw exn;\n  }\n}\n\nif (exit === 1) {\n  console.log(item);\n}\n'))),(0,s.kt)("h3",o({},{id:"match-on-array"}),"Match on Array"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),'let students = ["Jane", "Harvey", "Patrick"]\nswitch students {\n| [] => Js.log("There are no students")\n| [student1] =>\n  Js.log("There\'s a single student here: " ++ student1)\n| manyStudents =>\n  // display the array of names\n  Js.log2("The students are: ", manyStudents)\n}\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'var students = ["Jane", "Harvey", "Patrick"];\n\nvar len = students.length;\n\nif (len !== 1) {\n  if (len !== 0) {\n    console.log("The students are: ", students);\n  } else {\n    console.log("There are no students");\n  }\n} else {\n  var student1 = students[0];\n  console.log("There\'s a single student here: " + student1);\n}\n'))),(0,s.kt)("h3",o({},{id:"match-on-list"}),"Match on List"),(0,s.kt)("p",null,"Pattern matching on list is similar to array, but with the extra feature of extracting the tail of a list (all elements except the first one):"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),'let rec printStudents = (students) => {\n  switch students {\n  | list{} => () // done\n  | list{student} => Js.log("Last student: " ++ student)\n  | list{student1, ...otherStudents} =>\n    Js.log(student1)\n    printStudents(otherStudents)\n  }\n}\nprintStudents(list{"Jane", "Harvey", "Patrick"})\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'function printStudents(_students) {\n  while(true) {\n    var students = _students;\n    if (!students) {\n      return;\n    }\n    var otherStudents = students.tl;\n    var student = students.hd;\n    if (otherStudents) {\n      console.log(student);\n      _students = otherStudents;\n      continue;\n    }\n    console.log("Last student: " + student);\n    return;\n  };\n}\n\nprintStudents({\n  hd: "Jane",\n  tl: {\n    hd: "Harvey",\n    tl: {\n      hd: "Patrick",\n      tl: /* [] */0\n    }\n  }\n});\n'))),(0,s.kt)("h3",o({},{id:"small-pitfall"}),"Small Pitfall"),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Note"),": you can only pass literals (i.e. concrete values) as a pattern, not let-binding names or other things. The following doesn't work as expected:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),"let coordinates = (10, 20, 30)\nlet centerY = 20\nswitch coordinates {\n| (x, centerY, _) => Js.log(x)\n}\n")),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),"var coordinates = [10, 20, 30];\nvar centerY = 20;\n\nconsole.log(10);\n"))),(0,s.kt)("p",null,"A first time ReScript user might accidentally write that code, assuming that it's matching on ",(0,s.kt)("inlineCode",{parentName:"p"},"coordinates")," when the second value is of the same value as ",(0,s.kt)("inlineCode",{parentName:"p"},"centerY"),". In reality, this is interpreted as matching on coordinates and assigning the second value of the tuple to the name ",(0,s.kt)("inlineCode",{parentName:"p"},"centerY"),", which isn't what's intended."),(0,s.kt)("h2",o({},{id:"exhaustiveness-check"}),"Exhaustiveness Check"),(0,s.kt)("p",null,"As if the above features aren't enough, ReScript also provides arguably the most important pattern matching feature: ",(0,s.kt)("strong",{parentName:"p"},"compile-time check of missing patterns"),"."),(0,s.kt)("p",null,"Let's revisit one of the above examples:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res"}),'let message = switch person1 {\n| Teacher({name: "Mary" | "Joe"}) =>\n  `Hey, still going to the party on Saturday?`\n| Student({name, reportCard: {passing: true, gpa}}) =>\n  `Congrats ${name}, nice GPA of ${Js.Float.toString(gpa)} you got there!`\n| Student({\n    reportCard: {gpa: 0.0},\n    status: Vacations(daysLeft) | Sabbatical(daysLeft)\n  }) =>\n  `Come back in ${Js.Int.toString(daysLeft)} days!`\n| Student({status: Sick}) =>\n  `How are you feeling?`\n| Student({name}) =>\n  `Good luck next semester ${name}!`\n}\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'if (person1.TAG) {\n  var match$1 = person1.status;\n  var name = person1.name;\n  var match$2 = person1.reportCard;\n  if (match$2.passing) {\n    "Congrats " + name + ", nice GPA of " + match$2.gpa.toString() + " you got there!";\n  } else if (typeof match$1 === "number") {\n    if (match$1 !== 0) {\n      "Good luck next semester " + name + "!";\n    } else {\n      "How are you feeling?";\n    }\n  } else if (person1.reportCard.gpa !== 0.0) {\n    "Good luck next semester " + name + "!";\n  } else {\n    "Come back in " + match$1._0.toString() + " days!";\n  }\n} else {\n  switch (person1.name) {\n    case "Joe":\n    case "Mary":\n      break;\n    default:\n      throw {\n        RE_EXN_ID: "Match_failure",\n        _1: [\n          "playground.res",\n          13,\n          0\n        ],\n        Error: new Error()\n      };\n  }\n}\n'))),(0,s.kt)("p",null,"Did you see what we removed? This time, we've omitted the handling of the case where ",(0,s.kt)("inlineCode",{parentName:"p"},"person1")," is ",(0,s.kt)("inlineCode",{parentName:"p"},"Teacher({name})")," when ",(0,s.kt)("inlineCode",{parentName:"p"},"name")," isn't Mary or Joe."),(0,s.kt)("p",null,"Failing to handle every scenario of a value likely constitutes the majority of program bugs out there. This happens very often when you refactor a piece of code someone else wrote. Fortunately for ReScript, the compiler will tell you so:"),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{}),'Warning 8: this pattern-matching is not exhaustive.\nHere is an example of a value that is not matched:\nSome({name: ""})\n')),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"BAM"),"! You've just erased an entire category of important bugs before you even ran the code. In fact, this is how most of nullable values is handled:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),'let myNullableValue = Some(5)\n\nswitch myNullableValue {\n| Some(v) => Js.log("value is present")\n| None => Js.log("value is absent")\n}\n')),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),'var myNullableValue = 5;\n\nif (myNullableValue !== undefined) {\n  console.log("value is present");\n} else {\n  console.log("value is absent");\n}\n'))),(0,s.kt)("p",null,"If you don't handle the ",(0,s.kt)("inlineCode",{parentName:"p"},"None")," case, the compiler warns. No more ",(0,s.kt)("inlineCode",{parentName:"p"},"undefined")," bugs in your code!"),(0,s.kt)("h2",o({},{id:"conclusion--tips--tricks"}),"Conclusion & Tips & Tricks"),(0,s.kt)("p",null,"Hopefully you can see how pattern matching is a game changer for writing correct code, through the concise destructuring syntax, the proper conditions handling of ",(0,s.kt)("inlineCode",{parentName:"p"},"switch"),", and the static exhaustiveness check."),(0,s.kt)("p",null,"Here are some advices."),(0,s.kt)("p",null,"Do not abuse the wildcard ",(0,s.kt)("inlineCode",{parentName:"p"},"_")," too much. This prevents the compiler from giving you better exhaustiveness check, which would be especially important after a refactoring where you add a new case to a variant. Try only using ",(0,s.kt)("inlineCode",{parentName:"p"},"_")," against infinite possibilities, e.g. string, int, etc."),(0,s.kt)("p",null,"Use ",(0,s.kt)("inlineCode",{parentName:"p"},"if")," clause sparingly."),(0,s.kt)("p",null,(0,s.kt)("strong",{parentName:"p"},"Flatten your pattern-match whenever you can"),". This is a real bug remover. Here's a series of examples, from worst to best:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),"let optionBoolToBool = opt => {\n  if opt == None {\n    false\n  } else if opt === Some(true) {\n    true\n  } else {\n    false\n  }\n}\n")),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),"function optionBoolToBool(opt) {\n  if (opt === undefined) {\n    return false;\n  } else {\n    return opt === true;\n  }\n}\n"))),(0,s.kt)("p",null,"Now that's just silly =). Let's turn it into pattern-matching:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),"let optionBoolToBool = opt => {\n  switch opt {\n  | None => false\n  | Some(a) => a ? true : false\n  }\n}\n")),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),"function optionBoolToBool(opt) {\n  if (opt !== undefined && opt) {\n    return true;\n  } else {\n    return false;\n  }\n}\n"))),(0,s.kt)("p",null,"Slightly better, but still nested. Pattern-matching allows you to do this:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),"let optionBoolToBool = opt => {\n  switch opt {\n  | None => false\n  | Some(true) => true\n  | Some(false) => false\n  }\n}\n")),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),"function optionBoolToBool(opt) {\n  if (opt !== undefined && opt) {\n    return true;\n  } else {\n    return false;\n  }\n}\n"))),(0,s.kt)("p",null,"Much more linear-looking! Now, you might be tempted to do this:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),"let optionBoolToBool = opt => {\n  switch opt {\n  | Some(true) => true\n  | _ => false\n  }\n}\n")),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),"function optionBoolToBool(opt) {\n  if (opt !== undefined && opt) {\n    return true;\n  } else {\n    return false;\n  }\n}\n"))),(0,s.kt)("p",null,"Which is much more concise, but kills the exhaustiveness check mentioned above; refrain from using that. This is the best:"),(0,s.kt)(p,{labels:["ReScript","JS Output"],mdxType:"CodeTab"},(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-res",metastring:"example",example:!0}),"let optionBoolToBool = opt => {\n  switch opt {\n  | Some(trueOrFalse) => trueOrFalse\n  | None => false\n  }\n}\n")),(0,s.kt)("pre",null,(0,s.kt)("code",o({parentName:"pre"},{className:"language-js"}),"function optionBoolToBool(opt) {\n  if (opt !== undefined) {\n    return opt;\n  } else {\n    return false;\n  }\n}\n"))),(0,s.kt)("p",null,"Pretty darn hard to make a mistake in this code at this point! Whenever you'd like to use an if-else with many branches, prefer pattern matching instead. It's more concise and ",(0,s.kt)("a",o({parentName:"p"},{href:"variant#design-decisions"}),"performant")," too."))}c.isMDXComponent=!0,c.frontmatter={title:"Pattern Matching / Destructuring",description:"Pattern matching and destructuring complex data structures in ReScript",canonical:"/docs/manual/latest/pattern-matching-destructuring",__ghEditHref:"https://github.com/reason-association/rescript-lang.org/blob/master/pages/docs/manual/latest/pattern-matching-destructuring.mdx"}},25:function(e,t,n){(window.__NEXT_P=window.__NEXT_P||[]).push(["/docs/manual/latest/pattern-matching-destructuring",function(){return n(92304)}])}},function(e){e.O(0,[92888,49774,40179],(function(){return t=25,e(e.s=t);var t}));var t=e.O();_N_E=t}]);