Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a user inputted value in my Function in 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)

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.

like image 279
Marc Karam Avatar asked Sep 10 '16 19:09

Marc Karam


People also ask

How do you use user input in a function?

Python user input from the keyboard can be read using the input() built-in function. The input from the user is read as a string and can be assigned to a variable. After entering the value from the keyboard, we have to press the “Enter” button. Then the input() function reads the value entered by the user.

How do you take user input from a function in Python?

Python Input() vs raw_input() In Python 2, we can use both the input() and raw_input() function to accept user input. In Python 3, the raw_input() function of Python 2 is renamed to input() and the original input() function is removed.

What is the function to read any input from user?

Method 1: Using readline() function is a built-in function in PHP. This function is used to read console input.

What function can be used to take a value from the user?

In C programming, scanf() is one of the commonly used function to take input from the user.


1 Answers

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))

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.

like image 91
Gus Avatar answered Nov 15 '22 06:11

Gus