I'm trying to write a simple F# function that I can pass an array into and then print the values, but I'm having trouble. Here is what I have so far:
let a = [| a; b; c; d |];;
let f arrayFunction (string[] array) = function
for b=0 to array.Length
Console.WriteLine(array.[]);;
The F# syntax for defining parameters is backwards from the C# syntax; in F#, the name of the parameter comes first, then the type (with a colon to separate the two).
You also don't need the function keyword here, just the normal let binding -- function is for creating anonymous pattern-matching functions. You do, however, need to add a do at the end of the line in your for loop. Finally, the value after the to in an F# for loop is inclusive -- so you need to subtract one from the array length or you'll end up raising an IndexOutOfRangeException.
Your function should be written like this:
let a = [| a; b; c; d |];;
let f arrayFunction (array : string[]) =
for b = 0 to array.Length - 1 do
Console.WriteLine (array.[b]);;
Jack's answer is exactly correct however there are built-in functions in F# to do these kinds of tasks. In this instance we can send the array to Array.iter which will iterate over each item and pass the item into a string -> unit function.
So an example might look like this:
let a = [| "a"; "b"; "c"; "d" |];;
let f arrayFunction (array : string[]) =
array |> Array.iter arrayFunction;;
a |> f Console.WriteLine;;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With