3

I want to make something like it (Nemerle syntax)

def something =
match(STT)
    | 1 with st= "Summ"
    | 2 with st= "AVG" =>
        $"$st : $(summbycol(counter,STT))"

on F# so is it real with F#?

apaderno
  • 28,547
  • 16
  • 75
  • 90
cnd
  • 32,616
  • 62
  • 183
  • 313

2 Answers2

13

There is no direct support for that but you can mimic the effect like this as well:

let 1, st, _ | 2, _, st = stt, "Summ", "AVG"
sprintf "%s %a" st summbycol (counter, stt)
J D
  • 48,105
  • 13
  • 171
  • 274
  • 2
    Very interesting: you can use pattern matching with alternatives, without using the `match` or `function` keywords. I wonder whether this is an official feature? – wmeyer Dec 29 '10 at 14:04
  • 3
    @wmeyer: This is very much an official feature. The idea that patterns only appear after `match` or `function` expressions is a common misconception. Function arguments are also patterns so you can write `let f((a, b), (c, d)) = ..`. This is one of the biggest advancements ML made over Lisp. – J D Dec 29 '10 at 18:18
  • 1
    @aneccodeal Vanilla OCaml. Try `let 1, st, _ | 2, _, st = 1, "Summ", "AVG";;` and `let 1, st, _ | 2, _, st = 2, "Summ", "AVG";;`. – J D Mar 11 '12 at 04:47
  • @JonHarrop any chance how to get rid off the warning? "stdin(2,5): warning FS0025: Incomplete pattern matches on this expression. For example, the value '(0,_,_)' may indicate a case not covered by the pattern(s)." – stej Mar 13 '12 at 21:06
  • @stej You probably want to replace the literal `2` pattern with the catchall `_` in the second half of the or-pattern. – J D Mar 13 '12 at 21:48
8

If I understand you correctly, you'd like to assign some value to a variable as part of the pattern. There is no direct support for this in F#, but you can define a parameterized active pattern that does that:

let (|Let|) v e = (v, e)

match stt with 
| Let "Summ" (st, 1) 
| Let "AVG" (st, 2) -> srintf "%s ..." st

The string after Let is a parameter of the pattern (and is passed in as value of v). The pattern then returns a tuple containing the bound value and the original value (so you can match the original value in the second parameter of the tuple.

Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553