F# match with ->
Asked Answered
S

2

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#?

Sulky answered 28/12, 2010 at 9:8 Comment(0)
J
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.

Jahn answered 28/12, 2010 at 9:34 Comment(2)
One thing I've learned about F#: active patterns can do anything :)Natie
@Juliet: Yeah, they are really powerful.Pericarp
P
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)
Pericarp answered 28/12, 2010 at 13:21 Comment(5)
Very interesting: you can use pattern matching with alternatives, without using the match or function keywords. I wonder whether this is an official feature?Sadesadella
@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.Pericarp
@aneccodeal Vanilla OCaml. Try let 1, st, _ | 2, _, st = 1, "Summ", "AVG";; and let 1, st, _ | 2, _, st = 2, "Summ", "AVG";;.Pericarp
@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)."Gramineous
@Gramineous You probably want to replace the literal 2 pattern with the catchall _ in the second half of the or-pattern.Pericarp
J
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.

Jahn answered 28/12, 2010 at 9:34 Comment(2)
One thing I've learned about F#: active patterns can do anything :)Natie
@Juliet: Yeah, they are really powerful.Pericarp

© 2022 - 2024 — McMap. All rights reserved.