F # Convert 'discriminated union to string

I am trying to convert a discriminated union to a string, but I do not understand why this code does not work.

type 'a sampleType =
 | A of 'a
 | B of 'a

let sampleTypeToString x =
 match x with
 | A (value) -> string value
 | B (value) -> string value

This is fsharp interactive output.

sampleTypeToString A(2);;
 Stopped due to error
 System.Exception: Operation could not be completed due to earlier error
 Successive arguments should be separated by spaces or tupled, and arguments involving function or method applications should be parenthesized at 3,19
 This expression was expected to have type
     'obj'    
 but here has type
     'int'     at 3,21
+2
source share
1 answer

There are two errors here: the syntax of a functional application and the lost versatility.

Function Syntax Syntax

This is the error "function arguments must be separated by spaces or alternating ..."

In the expression sampleTypeToString A(2)you actually have three words, not two:

  • sampleTypeToString
  • A
  • (2)

A (2) . , -, " ". A (2) .

, sampleTypeToString A(2) sampleTypeToString, - A (2). , , , sampleTypeToString , A , .

- , :

   sampleTypeToString (A(2))

, , ( ) F # , :

   sampleTypeToString (A 2)

:

   sampleTypeToString <| A(2)

, , - ( ), A(2) sampleTypeToString.

" obj, int"

. , string sampleTypeToString? , . . , , .

sampleTypeToString sampleType<'a>, , string, 'a. string : , 'a. , , . , 'a, obj.

sampleTypeToString sampleType<obj>, sampleType<'a>, .

? inline. .NET, , ( DEFINE C ++). , 'a , picky string.

let inline sampleTypeToString x =
 match x with
 | A (value) -> string value
 | B (value) -> string value

sampleTypeToString (A 2)
sampleTypeToString (B "abc")
sampleTypeToString (A true)

string, obj:

let sampleTypeToString x =
 match x with
 | A (value) -> string (box value)
 | B (value) -> string (box value)

string, , - . , obj.ToString(). , .

, string .ToString() :

let sampleTypeToString x =
 match x with
 | A (value) -> value.ToString()
 | B (value) -> value.ToString()

, , string.

+6

Source: https://habr.com/ru/post/1674178/


All Articles