gpt4 book ai didi

F# 按类型进行模式匹配

转载 作者:行者123 更新时间:2023-12-04 23:56:02 25 4
gpt4 key购买 nike

按参数类型进行模式匹配如何在 F# 中工作?

例如,我正在尝试编写简单的程序,如果提供数字,则计算平方根,否则返回它的参数。

open System

let my_sqrt x =
match x with
| :? float as f -> sqrt f
| _ -> x


printfn "Enter x"
let x = Console.ReadLine()

printfn "For x = %A result is %A" x (my_sqrt x)

Console.ReadLine()

我收到此错误:
error FS0008: This runtime coercion or type test from type
'a
to
float
involves an indeterminate type based on information prior
to this program point. Runtime type tests are not allowed
on some types. Further type annotations are needed.

sqrtfloat 合作我检查 float类型,但猜测可能有更好的解决方案 - 比如检查输入是否为数字(一般情况下),如果是,则将其转换为浮点数?

最佳答案

这里的问题是 x 的类型实际上是 string .补充说它来自Console.ReadLine ,该字符串中存储的信息类型只能在运行时确定。这意味着你不能在这里使用模式匹配,也不能使用强制模式匹配。

但是你可以使用 Active Patterns .作为实际数据存储在x仅在运行时才知道,您必须解析字符串并查看包含的内容。

所以假设你期待一个 float ,但您无法确定,因为用户可以输入他们想要的任何内容。我们将尝试解析我们的字符串:

let my_sqrt x =
let success, v = System.Single.TryParse x // the float in F# is represented by System.Single in .NET
if success then sqrt v
else x

但这不会编译:

This expression was expected to have type float32 but here has type string



问题是编译器推断函数返回 float32 , 基于表达式 sqrt (System.Single.Parse(x)) .但是如果 x不解析为 float ,我们打算只返回它,作为 x是我们这里不一致的字符串。

为了解决这个问题,我们必须转换 sqrt 的结果到一个字符串:
let my_sqrt x =
let success, v = System.Single.TryParse x
if success then (sqrt v).ToString()
else x

好的,这应该有效,但它不使用模式匹配。所以让我们定义我们的“事件”模式,因为我们不能在这里使用常规模式匹配:
let (|Float|_|) input =
match System.Single.TryParse input with
| true, v -> Some v
| _ -> None

基本上,此模式仅在 input 时才匹配可以正确解析为浮点文字。以下是它在您的初始函数实现中的使用方法:
let my_sqrt' x =
match x with
| Float f -> (sqrt f).ToString()
| _ -> x

这看起来很像你的函数,但请注意,我仍然必须添加 .ToString()少量。

希望这可以帮助。

关于F# 按类型进行模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16668106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com