Unwrap F # Disposable Discriminated Join Type

We can expand the type of the type type Address = Address of stringusing the expand function, for example

let unwrapAddress (Address a) = a
let addr = Address "sdf"
let str = unwrapAddress addr

therefore, it strwill have a type string, but if there is a type such as this approach will not work:

type Composite = Composite of integer:int * someStr:string
let unwrap (Composite c) = c

will result in an error

let unwrap (Composite c) = c;;
------------^^^^^^^^^^^
error FS0019: This constructor is applied to 1 argument(s) but expects 2

Is there any way to decompose composite types into a simple tuple?

+6
source share
3 answers

It all works for me. This is your matching syntax, which you will most often find with matching operators, but this is on lhs jobs. Perhaps this makes sense, initially, for tuples, but you can use it with any structure.

let (a,b) = (1,2)

let (x,_) = (4,5)

:

let (head::tail) = [1;2;3;4]

FSI FS0025: . , "[]" , (-).

" , - ." ". (. , , --warnaserror +: 25). . . , -.

+ l.h.s. . . , .

let f (Composite(x,y)) = sprintf "Composite(%i,%s)" x y

f (Composite(1,"one"))

> val it : string = "Composite(1,one)"

:

type Address = Address of string //using unwrapping function like

let unwrapAddress (Address a) = a
let addr = Address "sdf"
let str = unwrapAddress addr

type Composite = Composite of integer:int * someStr:string
let unwrap (Composite(c,_)) = c
let cval = Composite(1,"blah")
unwrap cval

:

let xy = Composite(1,"abc") |> function (Composite(x,y))->(x,y)

... , DU...

let (|Composite|) = function | Composite(x,y)->(x,y)

let unwrap (Composite(x)) = x

let unwrap2 (Composite(x,y)) = (x,y)

... DU, - Active Pattern

, Composite...

module Composite = 
  let unwrap = function | Composite(x,y)->(x,y)

-

, , : , () int ()

- val : → int

+3

:

type Composite = Composite of integer:int * someStr:string

. , , . , :

let unwrap (Composite(i, s)) = i, s

, . ( , - , , Item1 Item2.)

type Composite = Composite of (int * string)

unwrap :

let unwrap (Composite c) = c

, :

let unwrap (Composite(i, s)) = i, s

, - , A of (T1 * T2) A of T1 * T2, , - , , , System.Tuple<T1, T2>. , .

+6

:

type Composite = Composite of int * string 

let unwrap (Composite (a, b)) = a, b

:

let unwrap x = 
    match x with
    | Composite (a, b) -> a, b

, , F # inline, . DU, , , DU - .

, ( , ):

type Composite = Composite of int * string | JustString of string

let unwrapString (Composite (_, s) | JustString s) = s

But most of the time you map the pattern to simpler types, such as tuples:

let f (a, b, c) = ...

or even more curious:

let f () = ...

Here it ()is a coincidence with a sample of a single value of the unit type, and not some kind of “visual marker for a function without parameters”, as is often described.

+2
source

All Articles