top | item 37432606

(no title)

eric-wieser | 2 years ago

It has the following which means the same as what you wrote:

    do let x ← List.range' 1 10; return x^2

The syntax is flexible enough that you could build your own:

    macro "[" r:term "|" preamble:doElem "]" : term => `(do 
    $preamble; return $r)

    #eval [x^2 | let x ← List.range' 1 10]

discuss

order

kmill|2 years ago

Here's an extensible one I wrote a while back for just List, but I haven't tested it in a while:

    declare_syntax_cat compClause
    syntax "for " term " in " term : compClause
    syntax "if " term : compClause
    
    syntax "[" term " | " compClause,* "]" : term
    
    macro_rules
      | `([$t:term |]) => `([$t])
      | `([$t:term | for $x in $xs]) => `(List.map (λ $x => $t) $xs)
      | `([$t:term | if $x]) => `(if $x then [$t] else [])
      | `([$t:term | $c, $cs,*]) => `(List.join [[$t | $cs,*] | $c])
    
    #eval [x+1| for x in [1,2,3]]
    -- [2, 3, 4]
    #eval [4 | if 1 < 0]
    -- []
    #eval [4 | if 1 < 3]
    -- [4]
    #eval [(x, y) | for x in List.range 5, for y in List.range 5, if x + y <= 3]
    -- [(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (3, 0)]
(Your doElem idea is a good one though)

2pEXgD0fZ5cF|2 years ago

Huh that is really cool! Thanks for the example!