cs3110 / textbook

The CS 3110 Textbook, "OCaml Programming: Correct + Efficient + Beautiful"
Other
720 stars 132 forks source link

Issue on page /chapters/data/algebraic_data_types.html #120

Closed danielruc91 closed 1 year ago

danielruc91 commented 1 year ago

I am reading on this page that find this:

let area = function
  | Point _ -> 0.0
  | Circle (_, r) -> Float.pi *. (r ** 2.0)
  | Rect ((x1, y1), (x2, y2)) ->
      let w = x2 -. x1 in
      let h = y2 -. y1 in
      w *. h

let center = function
  | Point p -> p
  | Circle (p, _) -> p
  | Rect ((x1, y1), (x2, y2)) -> ((x2 +. x1) /. 2.0, (y2 +. y1) /. 2.0)

While the let x = function <some pattern matching> is intuitive at the first glance, I am not able to find syntax like this in previous chapters. By checking back, I believe the function definition syntax can be let f x = <funtion body> or let f = fun x-> <function body>.

Is this syntax introduced some where in previous chapters?

cionx commented 1 year ago

The code

let f = function
  …

is shorthand for

let f x =
  match x with
  …

This syntax is introduced in subsection 3.1.6 (Data and Types → Lists → Immediate matches).


To find out where this notation is introduced I first generated a list of all files that contain the string = function by using the command grep -rl '= function' src/chapters/ in the root of the repository. I then went through this generated list to figure out which file comes earliest in the book.

danielruc91 commented 1 year ago

Thanks very much! I indeed missed that section.