Reputation: 43
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.[]);;
Upvotes: 2
Views: 2928
Reputation: 7121
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;;
Upvotes: 3
Reputation: 2136
In addition to the other answers - you didn't need to specify the type of the array argument explicitly. Type inference normally handles it fine (depending on the wider context). So for example this works:
let a = [| "a"; "b"; "c"; "d" |]
let f arrayFunction array =
array |> Seq.iter arrayFunction
let printme s = printfn "%s" s
f printme a
Upvotes: 1
Reputation: 11525
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]);;
Upvotes: 6