Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Parsing F#为什么字符串转换失败并带有下划线_Parsing_F# - Fatal编程技术网

Parsing F#为什么字符串转换失败并带有下划线

Parsing F#为什么字符串转换失败并带有下划线,parsing,f#,Parsing,F#,管道到int在这里工作,但系统转换不工作,有什么特别的原因吗?应该使用哪种方法 printfn“%i”(“1_2”|>int) printfn“%i”(System.Int32.Parse(“1_2”)) 我正在使用.NETCore2.2 看起来像是第一个方法调用 FSharp.Core.dll!Microsoft.FSharp.Core.LanguagePrimitives.ParseInt32(字符串s) 第二个电话呢 System.Private.CoreLib.dll!int.Parse

管道到int在这里工作,但系统转换不工作,有什么特别的原因吗?应该使用哪种方法

printfn“%i”(“1_2”|>int)

printfn“%i”(System.Int32.Parse(“1_2”))

我正在使用.NETCore2.2

看起来像是第一个方法调用

FSharp.Core.dll!Microsoft.FSharp.Core.LanguagePrimitives.ParseInt32(字符串s)

第二个电话呢

System.Private.CoreLib.dll!int.Parse(字符串s)


因此,如果有人好奇,我会看看两者的区别。.NET核心dll不带下划线

System.Private.CoreLib.dll使用

    private static unsafe void StringToNumber(ReadOnlySpan<char> str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo info, bool parseDecimal)
    {
        Debug.Assert(info != null);
        fixed (char* stringPointer = &MemoryMarshal.GetReference(str))
        {
            char* p = stringPointer;
            if (!ParseNumber(ref p, p + str.Length, options, ref number, info, parseDecimal)
                || (p - stringPointer < str.Length && !TrailingZeros(str, (int)(p - stringPointer))))
            {
                throw new FormatException(SR.Format_InvalidString);
            }
        }
    }
在第一种情况下,
(“1_2”|>int)
您使用的是作为F原语的
int

在第二种情况下,
(System.Int32.Parse(“1#2”)
您使用的是
System.Int32
,它是一个.NET CLR,而不是专门的F类型


正如您在实现中发现的那样,这两种方法使用不同的规则来解析整数。

正如其他人所说,使用了两种不同的解析整数的实现,并且不一定会产生相同的结果。然而,人们可能会想,为什么F#允许
1_2
作为有效的int

我浏览了源代码的历史记录,发现它是在以下提交中实现的:

它是用来支持F#中的文字的,如下所示:

let x = 1_000_000
let y = 1000000

x = y // true
x和y是相等的,但是
1_000_000
多亏了下划线,它更容易理解为100万


因为它是如何实现的,所以它也泄漏到运行时中,现在
int“1\u 000\u 000”
parse成功

什么方式不起作用?第二种方式抛出System.FormatException:“输入字符串的格式不正确。”这是.NET Core 2.2。我不确定您希望得到什么样的答案。它们的行为不同,因为它们是具有不同实现的不同函数。第一个在解析数字之前删除下划线,另一个则没有。也许你真正的问题是为什么F#中有几个不同的字符串解析函数?对于这个问题,答案可能是因为F#混合了不同的传统,在.NET传统中,数字解析预期以一种方式工作,而在ML传统中,数字解析预期以另一种方式工作。我明白了,我想这是有道理的。所以,当我现在参考系统时,我知道我点击了.net核心dll,它可能与点击fsharp.core.dll有不同的观点
let x = 1_000_000
let y = 1000000

x = y // true