diff --git a/README.md b/README.md index e40e62b..4dc108c 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/reason/dynamically-create-a-printf-string-format.md b/reason/dynamically-create-a-printf-string-format.md new file mode 100644 index 0000000..96edb17 --- /dev/null +++ b/reason/dynamically-create-a-printf-string-format.md @@ -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)