does a tee function exist somewhere in F# library?

感情迁移 提交于 2019-12-09 03:29:25

问题


...or in FSharpx?

let tee sideEffect =
    fun x ->
        do sideEffect x
        x

The usage could be something like

f >> tee (printfn "F returned: %A") >> g >> h

Or is there another simple way to do this?

thanks!


回答1:


ExtCore includes a function called tap which does exactly what you want. I use it for primarily for inspecting intermediate values within an F# "pipeline" (hence the name).

For example:

[| 1;2;3 |]
|> Array.map (fun x -> x * 2)
|> tap (fun arr ->
    printfn "The mapped array values are: %A" arr)
|> doOtherStuffWithArray



回答2:


The closest I've seen is actually in WebSharper. The definition is:

let inline ( |>! ) x sideEffect =
    do sideEffect x
    x

Usage:

(x |>! printf "%A") |> nextFunc



回答3:


As far as I know, a function like this isn't defined anywhere in the F# core library - though the library is missing many standard functions that are quite easy to define yourself, so my recommendation would be just to add it somewhere in your project - your tee seems like the best way to go.

That said, I'd probably prefer using less declarative style if I need side-effects and write something like:

let fResult = f fInput
printfn "F returned: %A" fResult
fResult |> g |> h

This is just a matter of style, but I prefer declarative style for fully declarative code and imperative style when there are side-effects involved. As a bonus, using local variables makes debugging easier. But using a function like tee is an equally good alternative that many people in the F# community would prefer.



来源:https://stackoverflow.com/questions/26672033/does-a-tee-function-exist-somewhere-in-f-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!