r/fsharp • u/Crazy699 • Aug 20 '20
How to pass an function as argument to another functions
open System
let addOneMoreApple x =
x.ToString() + " Number of Apples"
let doSomething f x =
let y = f (x +1)
"hello" + y
[<EntryPoint>] let main argv =
printfn "Hello World from F#!"
printfn "%s" (doSomething addOneMoreApple 22)
//let abc =doSomething addOneMoreApple 0
// return an integer exit code
0"f" is an function which be called on doSomething . "f" requires an int variable . So I have defined addOneMoreApple which has an int argument.
How can i pass addOneMoreApple with int argument ?
Edit : Based on comment by The_Mystic , I have posted entire code and rearranged it . How can i call doSomething in main method?
Edit 2 : debugnik fixes to the program has been added . Error message on 22 with red squiggly says that " "This expression was expected to have type 'int' -> 'a' but here has type 'int'""
4
Aug 20 '20 edited Aug 20 '20
There're multiple errors, but none related to the problem you're asking about:
The line for
mainis indented one space when it shouldn't. Remember F# is indentation sensitive.mainhas to return anìntvalue, presumably0for success.If you're invoking a method on
Console, you need toopen Systemfirst.
Otherwise, the snippet works fine. Try working on code cleanliness, your indentation is messy (are you indenting by adding spaces manually?)
1
u/LetMeUseMyEmailFfs Aug 21 '20
Pro tip for the next time you ask a question: ‘it doesn’t work’ is useless; we already know that from the fact you’re asking a question.
What we need to know is: what are you seeing instead? Which error? Which unexpected behavior?
1
2
u/The_Mystic Aug 20 '20
I think you have to define addOneMoreApple before doSomething. Then you can call: doSomething addOneMoreApple x, where x is some integer. Hope that makes sense :))