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))
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.
@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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With