What does |> do?

坚强是说给别人听的谎言 提交于 2019-12-12 01:33:24

问题


From Real World OCaml, page 38(see https://realworldocaml.org/v1/en/html/variables-and-functions.html#prefix-and-infix-operators). It defines a function:

# let (|>) x f = f x ;;

and applied it to strings:

# let path = "/usr/bin:/usr/local/bin:/bin:/sbin";;
val path : string = "/usr/bin:/usr/local/bin:/bin:/sbin"
#   String.split ~on:':' path
  |> List.dedup ~compare:String.compare
  |> List.iter ~f:print_endline
  ;;
/bin
/sbin
/usr/bin
/usr/local/bin
- : unit = ()

I am wondering - what does the operator do, really? I am confused because List.iter is a function and print_endline is a function as well. Reading the code I do not see where String.compare or List.dedup operates on the given path string. I read the book over and over again, it says:

" It's not quite obvious at first what the purpose of this operator is: it just takes a value and a function and applies the function to the value. Despite that bland-sounding description, it has the useful role of a sequencing operator, similar in spirit to using the pipe character in the UNIX shell. Consider, for example, the following code for printing out the unique elements of your PATH. Note that List.dedup that follows removes duplicates from a list by sorting the list using the provided comparison function. "

But why would the two functions operates on "path" after all? Can someone enlighten me?


回答1:


Well, you're looking at the complete definition of this operator. It takes a value (at the left) and a function (at the right) and applies the function to the value. The use of a symbol starting with | means that the operator associates to the left. So a |> b |> c is equivalent to (a |> b) |> c.

It seems you're more confused by higher-order functions than by the |> operator. Yes, List.iter is a function, but it takes a function as its first argument. So it's no surprise that print_endline is a function also. In fact List.iter ~f: print_endline is also a function. This function is applied to the value of the previous part of the expression (a list). This is what |> does.

If it helps any, |> is intended to be similar to the | of the Unix command line. You can specify an initial value and a series of functions to be applied to it like a pipeline.



来源:https://stackoverflow.com/questions/23747891/what-does-do

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