I've got an array of strings, call it a
, where each individual string represents a number. I also have a function f : int -> int -> int
, which I want to use to "reduce a
to a single number". I would like to write:
a |> Array.reduce (fun x y -> f (int32 x) (int32 y))
but this does not work, because the type of "reduce" forbids me from returning integers from f
(since a
is an array of strings)
Is there a functional way to make this work without having to return a string from
f
or casting the string array to an int array beforehand?
Array.reduce
mapping firstIf you don't want to adapt your f
to handle strings, and you want to use Array.reduce
then yeah I guess you should convert first (and to be honest: it seems easier than doing it manually with your wrapper-lambda) - so why not just use
a
|> Array.map int32
|> Array.reduce f
instead?
if you are concerned with the overhead of producing an intermediate Array you can always switch Array.
with Seq.
to to it lazily:
a |> Seq.map int32 |> Seq.reduce f
Array.fold
aside from that you can always fold
to your hearts desire:
a |> Array.fold (fun n s -> n + int32 s) 0
so you might call this more functional or not ;)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments