Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Haskell

Idiom #215 Pad string on the left

Prepend extra character c at the beginning of string s to make sure its length is at least m.
The length is the number of characters, not the number of bytes.

--              BaseString      PadChar      MinOutputLength     PaddedString/Output
padLeft ::       String ->     Char ->          Int ->                String
padLeft s c m = let 
   isBaseLarger =  length s > m
   padder s c m False = [ c | _ <- [1..(m-length s)]] ++ s
   padder s _ _ True = s
      in 
         padder s c m isBaseLarger

The list comprehension makes a string of chars(c) of the padding length
s = s.PadLeft(m, c);

New implementation...