如何在F#的函数中使用用户输入的值 [英] How can I use a user inputted value in my Function in F#

查看:111
本文介绍了如何在F#的函数中使用用户输入的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图在F#中创建一个简单的阶乘函数,该函数使用从用户输入的值(使用控制台,我不知道这是否有区别),但是我似乎找不到任何解决方案才能在我的函数中使用用户的值.

So I'm trying to make a simple factorial function in F# that uses a value inputted from the user (using the console, I don't know if that makes any difference) but I can't seem to find any solution to be able to use the value from the user in my function.

    open System

    let rec fact x =
        if x < 1 then 1
        else x * fact (x - 1)

    let input = Console.ReadLine()
    Console.WriteLine(fact input)

它总是给我错误,提示此表达式应具有类型"int",但此处具有类型"string"".如果有人对如何使其正常工作有任何想法(或者至少可以告诉我将用户输入的值转换为INT所需做的事情,那将不胜感激.

It constantly gives me the error saying "This expression was expected to have type "int" but here has type "string"". If anyone has any idea on how to make it work properly (or at least can tell me what I need to do to convert my user inputted value into an INT, that would be greatly appreciated.

谢谢您的帮助.

推荐答案

F#不会为您自动转换,因此您需要解析字符串:

F# does no automatic conversions for you, so you'll need to parse the string:

open System

let rec fact x =
    if x < 1 then 1
    else x * fact (x - 1)

let input = Console.ReadLine()
Console.WriteLine(fact (Int32.Parse input))

理论上,您需要将其转换回字符串以进行打印,但它可以正常工作,因为Console.WriteLine的重载需要一个整数并进行转换.

In theory you would need to convert back to string to print it, but it works because there is an overload for Console.WriteLine that takes an integer and does the conversion.

这篇关于如何在F#的函数中使用用户输入的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆