Skip to content

Commit 26d060a

Browse files
committed
Add Dynamically Create A Printf String Format as a reasonml til
1 parent e591de5 commit 26d060a

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010
For a steady stream of TILs from a variety of rocketeers, checkout
1111
[til.hashrocket.com](https://til.hashrocket.com/).
1212

13-
_684 TILs and counting..._
13+
_685 TILs and counting..._
1414

1515
---
1616

@@ -503,6 +503,7 @@ _684 TILs and counting..._
503503

504504
- [Break Out Of A While Loop](reason/break-out-of-a-while-loop.md)
505505
- [Defining Variants With Constructor Arguments](reason/defining-variants-with-constructor-arguments.md)
506+
- [Dynamically Create A Printf String Format](reason/dynamically-create-a-printf-string-format.md)
506507
- [Exhaustive Pattern Matching Of List Variants](reason/exhaustive-pattern-matching-of-list-variants.md)
507508
- [Helping The Compiler Help Us With Variants](reason/helping-the-compiler-help-us-with-variants.md)
508509
- [Inline Component Styles With Reason React](reason/inline-component-styles-with-reason-react.md)
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Dynamically Create A Printf String Format
2+
3+
Formatting a string with `Printf` requires defining a format for that
4+
string.
5+
6+
```reason
7+
let str = Printf.sprintf("%6s", "dope");
8+
/* str => " dope" */
9+
```
10+
11+
The _format_ is the first argument. At compile-time it is interpreted as a
12+
`format6` type value.
13+
14+
So, what if you want a dynamically created _format_ value? Simply
15+
concatenating some strings together won't do it because then the type will
16+
be `string` and that's not going to compile.
17+
18+
The [`Scanf.format_from_string`](https://reasonml.github.io/api/Scanf.html)
19+
function can help.
20+
21+
```reason
22+
let some_num = 6;
23+
let format_str = "%" ++ string_of_int(some_num) ++ "s";
24+
let format = Scanf.format_from_string(format_str, "%s");
25+
26+
let str = Printf.sprintf(format, "dope");
27+
/* str => " dope" */
28+
```
29+
30+
We can convert our string that has the appearance of a format into an actual
31+
`format6` type. To do this, we have to tell `format_from_string` what types
32+
each of the formats is going to have -- hence the second argument `%s`.
33+
34+
[source](https://twitter.com/rickyvetter/status/1013476235253436417)

0 commit comments

Comments
 (0)