f# - Why can't I simplify this iteration through a list of members of a discriminated union? -


frequently 1 wants iterate (with either map, iter, or fold) through collection of heterogeneous objects (different types). 1 way deal create discriminated union, allows 1 create list objects suitably converted du cases. following code in simple example:

type mydu = | x1 of int             | x2 of float             | x3 of string  let bar (y: mydu) =     match y     | x1 x -> printfn "%a" x       | x2 x -> printfn "%a" x     | x3 x -> printfn "%a" x  [x1(1); x2(2.0); x3("3"); x1(4)] |> list.map bar |> ignore 

this code runs fine , prints

1 2.0 "3" 4 

great! wonder if 1 can avoid repeating call printfn. tried following , not compile:

let baz (y: mydu) =     match y     | x1 x | x2 x | x3 x -> printfn "%a" x // red squiggly line under x1 x 

the compiler issues message:

this expression expected have type 'int' here has type 'float'

i suspect avoiding repetition feasible must making basic mistake. suggestions?

you're not making mistake there, it's not f#'s type system allow.

you can have multiple patterns on left side of match case arrow, required bind same set of values (incl. types). here, x has different type each pattern, , that's enough compiler complain.

there ways alleviate pain (you have member on du return boxed value, or have active pattern boxing in match case), they're highly situational. splitting patterns separate cases , repeating right side each 1 of them better solution in vacuum.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -