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

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

问题描述

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

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""但这里有类型字符串".如果有人对如何使其正常工作有任何想法(或者至少可以告诉我需要做什么才能将用户输入的值转换为 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天全站免登陆