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.[]);;
3 Answers 3
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]);;
-
Wow That works perfect. Thank you so much for your help and explaination!John Oriely– John Oriely2013年04月28日 16:43:40 +00:00Commented Apr 28, 2013 at 16:43
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;;
-
oh great, thanks. And to call this function I can use: arraryFunction(a);; ?John Oriely– John Oriely2013年04月28日 23:38:07 +00:00Commented Apr 28, 2013 at 23:38
-
@JohnOriely arrayFunction (as in your example) is a parameter, in this case it is a parameter that is a function. I call the
f
function passing Console.WriteLine as the arrayFunction parameter in the last line of the example.Gary.S– Gary.S2013年04月29日 05:20:40 +00:00Commented Apr 29, 2013 at 5:20 -
@Gary.S If you know the input is an array, you should use Array.iter, not Seq.iter. The latter is slower because it uses an enumerator to traverse the array instead of a loop.Jack P.– Jack P.2013年04月29日 10:54:43 +00:00Commented Apr 29, 2013 at 10:54
-
@JackP. Thanks, not sure why I didn't do that to begin with.Gary.S– Gary.S2013年04月29日 16:25:18 +00:00Commented Apr 29, 2013 at 16:25
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