pattern matching - F# Match with complex type -


i'm new f# , i'm trying simple pattern matching complex type cannot find way of doing it. see pseudo code below explain pattern matching want do.

type vector= {x:int; y:int}  let calculatedirection vector =  match vector | vector.x=0 && vector.y>0 -> "n"    // pseudo code  | vector.x>0 && vector.y>0 -> "ne"   // pseudo code  | vector.x>0 && vector.y=0 -> "e"    // pseudo code  | vector.x>0 && vector.y<0 -> "se"   // pseudo code  | vector.x=0 && vector.y<0 -> "s"    // pseudo code  | vector.x<0 && vector.y<0 -> "sw"   // pseudo code  | vector.x<0 && vector.y=0 -> "w"    // pseudo code  | vector.x<0 && vector.y>0 -> "nw"   // pseudo code  | _ -> "error" 

i read few tutorials (https://fsharpforfunandprofit.com/posts/match-expression/) it's simple scenarios , not me much. or don't understand them clearly.

thanks in advance.

to match records, can use record match syntax, record construction syntax:

match vector | { x = x; y = y } -> sprintf "vector (%d, %d)" x y 

you can combine guards, too:

match vector | { x = 0; y = y } when y > 0 -> "n" | { x = x; y = y } when x > 0 && y > 0 -> "ne" | { x = x; y = 0 } when x > 0 -> "e" ... 

but looks bit ugly. ugliness, construct own matchers (aka "active patterns") - regular functions, can used matching. have kind of funny syntax:

let (|positive|_|) x = if x > 0 some() else none let (|negative|_|) x = if x < 0 some() else none  match vector | { x = 0; y = positive } -> "n" | { x = positive; y = positive } -> "ne" | { x = positive; y = 0 } -> "e" | { x = positive; y = negative } -> "se" ... 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -