Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left and Right String Alignment in Haskell

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))
like image 284
StackoverflowKovu Avatar asked Mar 19 '26 22:03

StackoverflowKovu


2 Answers

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.
like image 163
Willem Van Onsem Avatar answered Mar 22 '26 14:03

Willem Van Onsem


@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.)

like image 26
bradrn Avatar answered Mar 22 '26 12:03

bradrn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!