Pattern matching in OCaml allows simultaneous matching against list structure and extraction of components, where lists can only be nil (empty) or cons (head + tail), enabling recursive functions like sum, length, and append to be implemented by matching against these two patterns and recursively processing the tail.
Pattern Matching with Lists | OCaml Programming Tutorial
Added:we've seen that pattern matching lets us do two things simultaneously match against the shape of some data and extract some pieces of that data let's take a more careful look now at how to pattern match with lists there's two things a list can be either nil or the cons of an element onto another list those are actually the only two possibilities the only two ways of forming lists so when we pattern match against a list we are using pattern matching in one of those two ways maybe you want to determine whether a list is empty for example you could match against that list and say is it the empty list if so return true but if it's an element const onto another list say head cons tail you could return false let's work with that code a little bit here is the empty function you can hover it over it and see its type is alpha list arrow bool you give it a list of any kind of element and it will give you back a boolean match against that list if it's empty return true why did i write lst here is the name of it you might be tempted for example to write list i didn't do that because i don't want to confuse myself list is also a keyword for types i'd be allowed to use it here but i prefer not to i also tend to not use just the letter l which is a nice short abbreviation for the word list and it's tempting to use but in many fonts just the letter l tends to look like either an i or a one so i tend to stay away from that and write lst for a list here in the second pattern matching branch here i bound two pattern variables named head and tail i actually never ended up using those on the right hand side here so another way of writing this code would have been to instead of saying head and tail say underscore cons underscore there needs to be a piece of data there i don't care what it is i just want to throw it away and not bind it to a name that's what underscore does so this is another good implementation of this function of course it's still a little more work than i needed to do i could have just written underscore here without specifying the cons because no matter what the list is if it's not the empty list i want to return false so there's a few different ways of writing empty there let's try another function suppose i wanted to sum the elements of a list of an int list well i want to match that list with if the list is empty what is its sum let's say that the sum of an empty list is zero but suppose there's an element at the head of that list the first element in it and then there's a tail of that list the rest of the elements in the list what can i do well i definitely want to include h in the sum so that's h plus and now if only i had a way of getting the sum of all of the rest of the elements in that list because if so i could just you know whatever that is i could add it in at this point oh wait i do i could write some t if i made some a recursive function so this is a way now of recursing down the rest of the list and adding in the sum of the tail along with the head element of it okay so what's the type of this it's in list arrow int this is taking a list of integers and giving me back the sum of all of them what is h in here it's going to be an int because it's the head element of a list it is t it's an int list because it's the rest of the elements of that list which might be empty of course and when it is finally empty we get down to the base case here of the empty list let's try out that function what's the sum of the empty list it's zero what's the sum of one two three it's six as it should be there's an interesting directive built into utah called trace if you say trace and the name of a function it will show you the calls and returns from that function if i say sum one two three you actually get a nice little depiction here of exactly what's going on with the recursive calls first sum gets called with the input that's why the arrow is going to the left into the function of 1 2 3 that causes a recursive call on 2 3 the tail of one two three that itself causes a recursive call on the tail of two three that's just three and then finally a recursive call on the empty list that call produces a return which is zero and we add in three and then we add in another two and add in another one until we get back up to six as the final output value so if you want to see what's going on with recursive calls this is a nice way to do that when you're done if you don't want to see it being traced anymore you can say untrace and that will get rid of that output let's try writing another function for the length of a list let rec length a list i know it's going to need to be a recursive function match lst with what is the length of the empty list well it's zero what is the length of a list that contains a head element followed by some other elements well it's going to be one plus we've got one in there because there is a head element there's at least one element there plus whatever the length of that sub list is let's give that one a try the length of the empty list is in fact zero the length of the list one two three is three as it should be and as a third example let's write a function that appends two lists rec append list one list two b and now i should give you an example of what i mean by a pen because it could mean different things to different people i'd like to write a comment up here to document that meanwhile i have a compilation error here in order to make it so that i can continue writing some code without getting an error let me just temporarily put in a kind of dummy value here it's just going to return the empty list that's obviously not the implementation i want in the end but it's always good to be compiling let me document an example usage here append of the list one two three with four five six what i'm looking for to get here is the list one two three four five six okay so the idea here is to append the second list onto the end of the first list now all of this is still immutable i'm not changing any of these lists i'm just returning a new list that happens to have all of the values from the first list followed by all the values from the second list okay so now that we know what we want to do let's write the function i'm going to match against that first list if it's empty then there are no more elements from it to take all i would need to do is return whatever happens to be in the second list at that point so i can return list two but if there's a head followed by a tail element then i at least want that head element followed by well if only i had a way of creating the list that had all the elements of t followed by all the elements of list two oh wait i do i have append since i'm writing it recursively so i can now append t and list two together now i wrote that in parentheses because i was worried that not everyone would be able to parse that right away and maybe even ocam wouldn't parse it correctly right away as it turns out i can leave off those parentheses this is the sort of thing you can play with to figure out as you get used to ocamel and that's because the cons operator is parsed at a very low level of precedence append is going to be applied to t and list 2 before the cons operation actually happens let's check out that code in utop if i append the list 1 2 3 with the list four five six i get the list one two three four five six as i want it by the way many of these list functions are built into the standard library in ocamel including append and append is even available as a built-in operator written just as the single at sign so instead of writing append one two three four five six i could write one two three at or append four five six and that gets me the same list and it's implemented exactly as i've shown you here
Up Next

OCaml Tuples Records Algebraic Data Types Tutorial
@dbroman
1.3K views•2021-11-03

BitTorrent Protocol Explained: Piece Selection & Peer Choking
@StevenGordonAU
481 views•2013-02-22

HM Type Inference: Constants and Names | OCaml Programming
@MichaelRyanClarkson
2.7K views•2021-08-08

Enigma Machine Mechanics: WWII Encryption Explained
@JaredOwen
13.2M views•2021-12-11
Related Study Plans & Knowledge Roadmaps
Structured learning paths in Computer Science

































![KOTLIN: Curso ANDROID desde CERO - SENTENCIA WHEN - Lección 4 [2020] | Español | MoureDev](https://i.ytimg.com/vi_webp/ufsrPf7vao4/sddefault.webp)









