Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip margin of indented triple-quote string in Purescript?

Tags:

purescript

When using triple quotes in an indented position I for sure get indentation in the output js string too:

Comparing these two in a nested let

let input1 = "T1\nX55.555Y-44.444\nX52.324Y-40.386"
let input2 = """T1
        X66.324Y-40.386
        X52.324Y-40.386"""

giving

// single quotes with \n
"T1\x0aX55.555Y-44.444\x0aX52.324Y-40.386"

// triple quoted
"T1\x0a        X66.324Y-40.386\x0a        X52.324Y-40.386"

Is there any agreed upon thing like stripMargin in Scala so I can use those without having to unindent to top level?

Update, just to clarify what I mean, I'm currently doing:

    describe "header" do
      it "should parse example header" do
        let input = """M48
;DRILL file {KiCad 4.0.7} date Wednesday, 31 January 2018 'AMt' 11:08:53
;FORMAT={-:-/ absolute / metric / decimal}
FMAT,2
METRIC,TZ
T1C0.300
T2C0.400
T3C0.600
T4C0.800
T5C1.000
T6C1.016
T7C3.400
%
"""
        doesParse input header
    describe "hole" do
      it "should parse a simple hole" do
        doesParse "X52.324Y-40.386" hole

Update:

I was asked to clarify stripMargin from Scala. It's used like so:

val speech = """T1
                |X66.324Y-40.386
                |X52.324Y-40.386""".stripMargin

which then removes the leading whitespace. stripMargin can take any separator, but defaults to |.

More examples:

Rust has https://docs.rs/trim-margin/0.1.0/trim_margin/ Kotlin has in stdlib: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/trim-margin.html

I guess it might sound like asking for left-pad ( :) ) but if there's something there already I'd rather not brew it myself…

like image 351
Viktor Hedefalk Avatar asked Sep 14 '25 20:09

Viktor Hedefalk


1 Answers

I'm sorry you didn't get a prompt response to this one, but I have implemented this function here. In case the pull request isn't merged, here's an implementation that just depends on purescript-strings:

import Data.String (joinWith, split) as String
import Data.String.CodeUnits (drop, dropWhile) as String
import Data.String.Pattern (Pattern(..))

stripMargin :: String -> String
stripMargin =
  let
    lines = String.split (Pattern "\n")
    unlines = String.joinWith "\n"
    mapLines f = unlines <<< map f <<< lines
  in
    mapLines (String.drop 1 <<< String.dropWhile (_ /= '|'))
like image 105
Nick Saunders Avatar answered Sep 17 '25 18:09

Nick Saunders