Wednesday, 7 December 2016

Sign up How do I retreive a value when using the “function” syntax to perform pattern matching

The following line doesn't compile:
| IsNeither  -> sprintf "%i" // ???
Here's the function that this line belongs to:
let run = function

    | IsFizzBuzz -> "Fizz Buzz"
    | IsFizz     -> "Fizz"
    | IsBuzz     -> "Buzz"
    | IsNeither  -> sprintf "%i" // Doesn't compile
Here's the entire program: module Temp
let (|IsFizz|IsBuzz|IsFizzBuzz|IsNeither|) = function
    | n when n % 3 = 0 && 
             n % 5 = 0 -> IsFizzBuzz
    | n when n % 3 = 0 -> IsFizz
    | n when n % 5 = 0 -> IsBuzz
    | n ->                IsNeither

let run = function

    | IsFizzBuzz -> "Fizz Buzz"
    | IsFizz     -> "Fizz"
    | IsBuzz     -> "Buzz"
    | IsNeither  -> sprintf "%i" // Doesn't compile

let result = [1..16] |> List.map(run)
Can I still extract a value using the "function" syntax on the signature?
Example:
let (|IsFizz|IsBuzz|IsFizzBuzz|IsNeither|) = function

--------------------------------------------------------------------------------------------------------------- ----

Best Answer;



The easiest solution would be to make the value part of the pattern.
let (|IsFizz|IsBuzz|IsFizzBuzz|IsNeither|) = function
    | n when n % 3 = 0 && 
             n % 5 = 0 -> IsFizzBuzz
    | n when n % 3 = 0 -> IsFizz
    | n when n % 5 = 0 -> IsBuzz
    | n                -> IsNeither n

let run = function
    | IsFizzBuzz  -> "Fizz Buzz"
    | IsFizz      -> "Fizz"
    | IsBuzz      -> "Buzz"
    | IsNeither n -> sprintf "%i" n



No comments:

Post a Comment