简体   繁体   English

如何在没有给定类型声明的情况下测试 F# 中的原始类型和类型转换

[英]How to test for primitive types in F# and type cast without given type declarations

这是我认为通过模式匹配对任何类型进行类型检查的更好方法,而不是我见过的所有其他方法。

If you need a way to easily check for primitive types如果您需要一种轻松检查原始类型的方法

I came up with it in my work making a Lexer and parser generator in F# without code generation and with DFA performance, and instant type checking.我在我的工作中想出了它,在 F# 中制作词法分析器和解析器生成器,无需代码生成,具有 DFA 性能和即时类型检查。

Assume that we have some syntaks tree where you don't know how it looks or even which types it contains, but you need to construct it at some point in time, and before that might need to have a collection of different types.假设我们有一些语法树,你不知道它的外观,甚至不知道它包含哪些类型,但你需要在某个时间点构造它,在此之前可能需要有不同类型的集合。

That is against F#'s general type system.这与 F# 的通用类型系统背道而驰。

I use obj which can be anything.我使用 obj 可以是任何东西。

type Type = Type of obj

we define a function type that simply delay the work我们定义了一个简单地延迟工作的函数类型

Type delay = Delay of (unit -> Type)

let inline AnyType t = Type (t :> obj)

We define a function that delays the work.我们定义了一个延迟工作的函数。

let Delay f input = 
    fun _ ->
       f input |> AnyType
    |> Delay

and a function invoking the work和调用工作的函数

let Do (Delay f) = f()

now assume that we have some lexeme (string conforming to a pattern) and the type现在假设我们有一些词素(符合模式的字符串)和类型

type TYPE = INT of int | FLOAT of float | Error

with the function与功能

let GetValue (Type t) =
    match (Type t) with
    | :? int as t -> INT t
    | :? float as t -> FLOAT t
    | _ -> ERROR

then we can do something like this那么我们可以做这样的事情

 let Float (str: string) = System.Double.Parse str
 let Int (str: string) = System.Int32.Parse str



let d = Delay Float "0.123" |> Do |> GetValue
let i = Delay Int "123" |> Do |> GetValue

without getting a compiletime type error.没有得到编译时类型错误。 This will of course lead to the programmer checking for type correctness in the program, but that would be needed anyway这当然会导致程序员检查程序中的类型正确性,但无论如何都需要

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM