Reputation: 541
So I have a function SolveEquasion that returns a pair float*float[]. What is the best way to print the number and the array and continue working with the array? I made the following code but it seems there is a better way
... |> SolveEquasion |> (fun (det, solution) -> printfn "Determinant = %f\nSolution = %A" det (Array.toList solution), solution ) |> snd
Upvotes: 3
Views: 1198
Reputation: 41
I think the original solution is fine, and we can improve its clarity by giving your anonymous function the name I've seen it given in some other libraries based around pipelining higher-order functions: tap.
let tap f x =
f x
x
(1.0, [| 2.0; 3.0 |])
|> tap (fun (s, a) -> printfn "%A %A" s a)
|> snd
Upvotes: 3
Reputation: 243041
I'd probably use Daniel's approach and just assign the value you want to print to a symbol using let
. Alternatively, you could define a variant of printf
that takes some arguments and returns one of them. I'm not sure if there is a general scheme how this should be done - for your example it would take a two-element tuple:
let mprintf fmt (a, b) =
Printf.kprintf (fun s -> printf "%s" s; (a, b)) fmt a b
Then you can write:
...
|> SolveEquasion
|> mprintfn "Determinant = %f\nSolution = %A"
|> snd |> // ... more stuff with solution
Upvotes: 0
Reputation: 55184
Well, for one thing you can skip the use of snd
by returning a single value rather than a tuple from the previous function:
...
|> SolveEquasion
|> (fun (det, solution) ->
printfn "Determinant = %f\nSolution = %A" det (Array.toList solution)
solution )
Upvotes: 1
Reputation: 47904
I don't think your solution can improved if you want to do this in a pipeline. Another approach is to use a let
binding, along with splitting up the pipelined operations, to avoid having a function that acts like the love child of map
and iter
.
let (det, solution) = SolveEquasion
printfn "Determinant = %f\nSolution = %A" det (Array.toList solution)
//do something else with solution
Upvotes: 3