Vlad
Vlad

Reputation: 146

How to execute a function?

I read a book called Real World Functional Programming with F# and C# and there is an example that goes like this

open System

let readInput() =      
    let s = Console.ReadLine()      
    let (succ, num) = Int32.TryParse(s)
    if (succ) then  
        Some(num)
    else          
        None

let readAndAdd1() =    
    match (readInput()) with 
    | None    -> None    
    | Some(n) -> 
        match (readInput()) with       
        | None    -> None       
        | Some(m) ->         
            Some(n + m)

printfn "Result - %A" readAndAdd1

It should ask you for two numbers and then add them together. But I don't seem to get it working. When I tried this in LinqPad even got an error when I typed readInput(). When I typed just readInput it asked me for the first value but not for the second one. In the F# Interactive it works but it prints out Result - <fun:it@20>

How can I run this method?

Upvotes: 0

Views: 145

Answers (1)

Petr
Petr

Reputation: 4280

When you are trying

printfn "Result - %A" readAndAdd1 

in F# interactive you provides printfn with identifier 'readAndAdd1' which is a function. If you need to print result of function call you should call this function like this:

printfn "Result - %A" (readAndAdd1())

in this case F# interactive will wait for two inputs and will print result afterward. F# interactive output:

> printfn "Result - %A" (readAndAdd1());;
2
3
Result - Some 5
val it : unit = ()
>

Upvotes: 3

Related Questions