Reputation:
type ColType = I of int | S of string | F of float
I know that you cannot return a different type from a pattern match which is why I made this type in the first place for a parser I am creating. However with this code:
//create i coltype
let m (x : int) : ColType =
ColType.I x
//create f coltype
let n (x : float) : ColType =
ColType.F x
//create s coltype
let b (x : string) : ColType =
ColType.S x
let pColType =
let innerFn (charList : char list) =
let i = String(List.toArray charList)
match i with
| "int" -> m
| "float" -> n
| "string" -> b
many1 parseLowercase |>> innerFn
It will still give me an error in the pColType function despite m, n and b returning the same type.
code such as parseLowercase etc is just code to get a string, this is functioning as intended, the problem is the return value not being the same despite all being coltype? (altough different states of it).
Upvotes: 1
Views: 42
Reputation: 5004
Like rmunn and Romanov mentioned your 3 functions are of different type. You can make them return a single type for instance obj -> ColType
using box
& unbox
:
let pColType =
let innerFn (charList : char list) =
let i = String(List.toArray charList)
match i with
| "int" -> unbox >> m
| "float" -> unbox >> n
| "string" -> unbox >> b
|_-> failwithf "error %A" i
many1 parseLowercase |>> innerFn
That requires that you box
the value before invoking the resulting function.
Since you are building a parser it makes more sense to instead make it return a string -> ColType
:
let pColType =
let innerFn (charList : char list) =
let i = String(List.toArray charList)
match i with
| "int" -> parseInt >> m
| "float" -> parseFloat >> n
| "string" -> parseString >> b
|_-> failwithf "error %A" i
many1 parseLowercase |>> innerFn
Upvotes: 1