0

I have a source code below. I don't understand its syntax. [g | t <- ts; g <- symbols t] is very strange. Please help me to explain it or recommend any books or documents which correlates to it. Thank you very much

type term = V of string | F of string * term list

let rec symbols = function
  | V x -> [x]
  | F (f, ts) -> f :: [ g | t <- ts; g <- symbols t ]

let rec functions = function
  | V _ -> []
  | F (f, ts) -> f :: [ g | t <- ts; g <- functions t ]
ivg
  • 34,431
  • 2
  • 35
  • 63
vent
  • 39
  • 7

1 Answers1

1

This is a non standard syntax for list comprehension. I don't know any book that documents it. The idea is that it should resemble set builder notation. In short, this expression will be evaluated to list:

 [ x | p <- expr; p * 2 - 1 ]

where expr should evaluate to lists, p would be assigned to the corresponding elements of the list, so that the p * 2 - 1 would be applied to each element of the original list.

In a normal OCaml syntax this can be expressed as

List.map (fun p -> p * 2 + 1) xs 

As a final note, I wouldn't suggest you to use this list comprehension notation. It doesn't have tooling support, first off all, and is not common in modern OCaml anyway.

P.S. And example expression

f :: [ g | t <- ts; g <- symbols t ]

in vanilla OCaml is

f :: List.(map symbols ts |> concat)
Community
  • 1
  • 1
ivg
  • 34,431
  • 2
  • 35
  • 63
  • It's suspicious. I think that this comprehention is more equal to `cartesian_product xs ys |> List.map (fun (x,y) -> x+y)` – Kakadu Mar 03 '15 at 11:26
  • yep, looks like that you're true, let me fix the post. Thanks – ivg Mar 03 '15 at 11:30
  • I think there is an issue again. Function `symbols` returns a list but you seems to expect a signle value. Maybe you need to add `concat` somewhere.... – Kakadu Mar 03 '15 at 11:34