Re: pattern matching with keyword function
"Douglas Lewit [email protected] [ocaml_beginners]" <[email protected]> Fri, 8 Apr 2016 12:10:36 -0500
| Newsgroups | gmane.comp.lang.ocaml.beginners |
|---|---|
| Message-ID | <CAM0XMJSp1AuEFZiykqMDo3uD=OdRshw+dWuWgCF3VYCohN6Fdw@mail.gmail.com> |
I think the first pipe is optional. I like to include it just because I think it looks better that way. But the first pipe is really optional. So you could define a piecewise linear function like this: *let** piecewise x **=* *match** x **with* *|**0* *->* *0* *|**x **when** x **<* *0* *->* *-**1* *|**x **when** x **>* *0* *->* *1* *;;* You don't have to write it that way. You could also write it this way if you eliminate the first pipe: *let** piecewise x **=* *match** x **with* *0* *->* *0* *|**x **when** x **<* *0* *->* *-**1* *|**x **when** x **>* *0* *->* *1* *;;* The only problem with my function definition is that it generates Warning Message #8 about a pattern matching that is not exhaustive. But if you look at the function, it really is exhaustive. An int is either 0, less than 0 or greater than 0. That's it! So I think the warning can be safely ignored. Best, Douglas. On Fri, Apr 8, 2016 at 3:50 AM, cedlemo [email protected] [ocaml_beginners] < [email protected]> wrote: > > > Hi, > > I have "stumbled" on this simple function > > let rec flatten = function > [] -> [] > | l::r -> l @ flatten r > > At first glance I asked myself why they don't use the last remaining > element of the list > then I see that the line > [] -> [] > > doesn't have any "|" at the beginning. > > Could you explain we how does that works? > And maybe could you give me one or more links for informations/examples > on the patterns matching > with the function keywords. > > Thanks > > cedlemo > >