Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a lazy string builder #607

Open
wants to merge 6 commits into
base: dev
Choose a base branch
from
Open

Conversation

TimWhiting
Copy link
Collaborator

@TimWhiting TimWhiting commented Nov 17, 2024

Hi @daanx,

Wanted to have some fun this weekend, and try out the new lazy constructors.

Ended up making this lazy string builder, partly inspired by your pretty print module.
Conversions / additions to string builder for polymorphic types are made using show for the type - but lazily.
You can always create a small method for any type to build it in a particular way, and use these basic building blocks just for combining.

I understand if this is not something you want in std/core, but I wanted to share.

@TimWhiting
Copy link
Collaborator Author

TimWhiting commented Nov 17, 2024

The sample code here:

Using |-| for spaces |.| for direct appending, \ for newline and \- for newline + indent.

import std/core/stringb
import std/num/float64

fun sb(l: list<int>)
  match l
    Nil -> build()
    Cons(x, Nil) ->
      x.build()
    Cons(x, xs) ->
      x |-| sb(xs)

fun tupled(l: list<a>, ?show: a -> string)
  "(" |.| tuprec(l) |.| ")".build()

fun tuprec(l : list<a>, ?show: a -> string)
  match l
    Nil -> build()
    Cons(x, Nil) ->
      x.build()
    Cons(x, xs) ->
      x |.| "," |-| tuprec(xs)

fun main()
  [1, 2, 3].sb.println
  "".println

  val b = "Hello" |-| "world!" |.|
            indented([1, 2, 3].sb \ [1, 2, 3].build()) |.|
            2 \ 4.5.build()
  b.println
  "".println

  val b1 = "Hello" |-| "world!" 
              \- [1, 2, 3].sb 
                \- [1, 2, 3].tupled
                  \- 2 
                  \ 4.5.build()
  b1.println

prints the following

1 2 3

Hello world!
  1 2 3
  [1,2,3]
2
4.5

Hello world!
  1 2 3
    (1, 2, 3)
      2
      4.5

Conversions / additions to string builder for polymorphic types are made using show for the type - but lazily.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant