F#奇怪的printfn问题

栏目: ASP.NET · 发布时间: 5年前

内容简介:翻译自:https://stackoverflow.com/questions/1038676/f-strange-printfn-problem

我正在玩F#(Visual Studio 2010 beta 1),我写了一个小的控制台脚本,要求用户输入2个数字和一个操作符,然后执行它.

它工作正常,除了一个微小但令人烦恼的事情:有时我的printfn指令被忽略.我在代码中放置了断点,以确定情况确实如此.

代码段:

let convert (source : string) =
    try System.Int32.Parse(source)
    with :? System.FormatException ->
        printfn "'%s' is not a number!" source;
        waitForExitKey();
        exit 1

let read =
    printfn "Please enter a number.";
    System.Console.ReadLine

let num1 : int = read() |> convert // the printfn in the read function is run...
let num2 : int = read() |> convert // ... but here is ignored

这当然不是完整的来源,但我认为这就足够了.如果您需要完整的来源,请告诉我.

所以我的问题很简单:printfn导致这个问题的原因是什么?难道我做错了什么?

提前致谢,

ShdNx

This page

部分解释了发生了什么,但简短而甜蜜的版本是F#如果不接受参数,将在声明上执行任何值.

let read =
    printfn "Please enter a number."
    System.Console.ReadLine

由于read不接受任何参数,因此它会在声明时立即执行,并将函数的返回值绑定到读取的标识符.

顺便提一下,您的返回值恰好是类型(单位 – >字符串)的函数.这是因为如果没有传递所有参数,F#会自动为 curries functions . ReadLine需要一个单元参数,但由于它没有被传递,所以实际上将read绑定到ReadLine函数本身.

解决方案如下:

let read() = // read takes one unit parameter
    printfn "Please enter a number."
    System.Console.ReadLine() // pass paramter to ReadLine method

由于read接受一个参数,因此每次调用时都会重新评估.另外,我们将一个参数传递给ReadLine,否则我们只会将ReadLine函数作为值返回.

翻译自:https://stackoverflow.com/questions/1038676/f-strange-printfn-problem


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

R for Data Science

R for Data Science

Hadley Wickham、Garrett Grolemund / O'Reilly Media / 2016-12-25 / USD 39.99

http://r4ds.had.co.nz/一起来看看 《R for Data Science》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

在线进制转换器
在线进制转换器

各进制数互转换器