3

I am used to working with Python and fairly new to Haskell.

I was wondering how strings are left/right aligned in Haskell and if there exist equivalent functions to the following Python functions in Haskell:

str = "Hello stackoverflow."

# Printing a left aligned string  
print (str.ljust(40)) 

# Printing a right aligned string  
print (str.rjust(40))
2
  • 1
    Pay attention to difference between String and Text! putStrLn takes String but decent alignment module exist only which takes Text. Commented Dec 15, 2020 at 20:26
  • 1
    Usually when such a thing is needed, the more abstract prettyprinter or boxes libraries are a better choice. Commented Dec 15, 2020 at 23:41

2 Answers 2

7

Typically for text processing, Text is used and not Strings, since Text works with an array of unboxed unicode characters. One can justify with justifyLeft :: Int -> Char -> Text -> Text and justifyRight :: Int -> Char -> Text -> Text. For example:

{-# LANGUAGE OverloadedStrings #-}

import Data.Text(Text, justifyLeft, justifyRight)
import Data.Text.IO as TI

myText :: Text
myText = "Hello stackoverflow."

main :: IO ()
main = do
    TI.putStrLn (justifyLeft 40 ' ' myText)
    TI.putStrLn (justifyRight 40 ' ' myText)

The ' ' is here the character used as "fill character". For example if we use justifyLeft 40 '#' myText and justifyRight 40 '#' myText instead, we get:

Hello stackoverflow.####################
####################Hello stackoverflow.
Sign up to request clarification or add additional context in comments.

Comments

3

@WillemVanOnsem has already given a good answer for how to justify Texts. But, for completeness, the equivalent functions for String (or indeed any list) are:

justifyLeft, justifyRight :: Int -> a -> [a] -> [a]
justifyLeft  n c s = s ++ replicate (n - length s) c
justifyRight n c s = replicate (n - length s) c ++ s

(I don’t believe these are predefined anywhere, but they’re easy enough to define yourself.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.