mirror of
https://github.com/jbranchaud/til
synced 2026-01-02 22:58:01 +00:00
Add Dynamically Create A Printf String Format as a reasonml til
This commit is contained in:
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
||||
For a steady stream of TILs from a variety of rocketeers, checkout
|
||||
[til.hashrocket.com](https://til.hashrocket.com/).
|
||||
|
||||
_684 TILs and counting..._
|
||||
_685 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -503,6 +503,7 @@ _684 TILs and counting..._
|
||||
|
||||
- [Break Out Of A While Loop](reason/break-out-of-a-while-loop.md)
|
||||
- [Defining Variants With Constructor Arguments](reason/defining-variants-with-constructor-arguments.md)
|
||||
- [Dynamically Create A Printf String Format](reason/dynamically-create-a-printf-string-format.md)
|
||||
- [Exhaustive Pattern Matching Of List Variants](reason/exhaustive-pattern-matching-of-list-variants.md)
|
||||
- [Helping The Compiler Help Us With Variants](reason/helping-the-compiler-help-us-with-variants.md)
|
||||
- [Inline Component Styles With Reason React](reason/inline-component-styles-with-reason-react.md)
|
||||
|
||||
34
reason/dynamically-create-a-printf-string-format.md
Normal file
34
reason/dynamically-create-a-printf-string-format.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# Dynamically Create A Printf String Format
|
||||
|
||||
Formatting a string with `Printf` requires defining a format for that
|
||||
string.
|
||||
|
||||
```reason
|
||||
let str = Printf.sprintf("%6s", "dope");
|
||||
/* str => " dope" */
|
||||
```
|
||||
|
||||
The _format_ is the first argument. At compile-time it is interpreted as a
|
||||
`format6` type value.
|
||||
|
||||
So, what if you want a dynamically created _format_ value? Simply
|
||||
concatenating some strings together won't do it because then the type will
|
||||
be `string` and that's not going to compile.
|
||||
|
||||
The [`Scanf.format_from_string`](https://reasonml.github.io/api/Scanf.html)
|
||||
function can help.
|
||||
|
||||
```reason
|
||||
let some_num = 6;
|
||||
let format_str = "%" ++ string_of_int(some_num) ++ "s";
|
||||
let format = Scanf.format_from_string(format_str, "%s");
|
||||
|
||||
let str = Printf.sprintf(format, "dope");
|
||||
/* str => " dope" */
|
||||
```
|
||||
|
||||
We can convert our string that has the appearance of a format into an actual
|
||||
`format6` type. To do this, we have to tell `format_from_string` what types
|
||||
each of the formats is going to have -- hence the second argument `%s`.
|
||||
|
||||
[source](https://twitter.com/rickyvetter/status/1013476235253436417)
|
||||
Reference in New Issue
Block a user