|
| 1 | +--- |
| 2 | +id: "pipe" |
| 3 | +keywords: ["pipe", "operator", "function", "argument"] |
| 4 | +name: "->" |
| 5 | +summary: "This is the `pipe` operator." |
| 6 | +category: "operators" |
| 7 | +--- |
| 8 | + |
| 9 | +The `->` operator passes a value into the first argument position of a function. Typically it's used to chain multiple function calls together in a "pipeline like" fashion. |
| 10 | + |
| 11 | +### Example |
| 12 | + |
| 13 | +<CodeTab labels={["ReScript", "JS Output"]}> |
| 14 | + |
| 15 | +```res |
| 16 | +let dieRoll = size => { |
| 17 | + Js.Math.random_int(1, size) |
| 18 | +} |
| 19 | +
|
| 20 | +let dieRollMessage = (value, name) => { |
| 21 | + "Hi " ++ name ++ ", you rolled a " ++ Js.Int.toString(value) |
| 22 | +} |
| 23 | +
|
| 24 | +let message = dieRoll(6)->dieRollMessage("Marshall") |
| 25 | +``` |
| 26 | + |
| 27 | +```js |
| 28 | +function dieRoll(size) { |
| 29 | + return Js_math.random_int(1, size); |
| 30 | +} |
| 31 | + |
| 32 | +function dieRollMessage(value, name) { |
| 33 | + return "Hi " + name + ", you rolled a " + value.toString(); |
| 34 | +} |
| 35 | + |
| 36 | +var message = dieRollMessage(Js_math.random_int(1, 6), "Marshall"); |
| 37 | +``` |
| 38 | + |
| 39 | +</CodeTab> |
| 40 | + |
| 41 | +Which produces a message such as `Hello Marshall, you rolled a 3`. |
| 42 | + |
| 43 | +You can also explicitly define the argument position of a piped value by using the `_` placeholder: |
| 44 | + |
| 45 | +<CodeTab labels={["ReScript", "JS Output"]}> |
| 46 | + |
| 47 | +```res example |
| 48 | +let logMsg = (user: string, datestr: string, msg: string): unit => { |
| 49 | + Js.log(`${user}|${datestr}|${msg}`) |
| 50 | +} |
| 51 | +
|
| 52 | +let datestr = "01-01-2021" |
| 53 | +let user = "admin" |
| 54 | +
|
| 55 | +// Here, we put the result of toUpperCase into the last position |
| 56 | +// denoted with an _ |
| 57 | +Js.String2.toUpperCase("example message")->logMsg(user, datestr, _) |
| 58 | +``` |
| 59 | + |
| 60 | +```js |
| 61 | +function logMsg(user, datestr, msg) { |
| 62 | + console.log(user + "|" + datestr + "|" + msg); |
| 63 | + |
| 64 | +} |
| 65 | + |
| 66 | +var datestr = "01-01-2021"; |
| 67 | + |
| 68 | +var user = "admin"; |
| 69 | + |
| 70 | +logMsg(user, datestr, "example message".toUpperCase()); |
| 71 | +``` |
| 72 | + |
| 73 | +</CodeTab> |
| 74 | + |
| 75 | +### References |
| 76 | + |
| 77 | +* [Pipe](/docs/manual/latest/pipe) |
0 commit comments