How to print the same char n times in Haskell

后端 未结 3 375
无人共我
无人共我 2021-01-21 00:01

I would like to print a char underlining a String n times, with n the length of the String in Haskell.

How should I do this?

My String is: \"Available Chars (x)\

相关标签:
3条回答
  • 2021-01-21 00:48

    A possibility is to (re)implement replicate, for instance as follows,

    replicate' :: Int -> a -> [a]                
    replicate' n x = if (n <= 0) then [] else (x : replicate (n-1) x) 
    
    0 讨论(0)
  • 2021-01-21 01:00

    got it!

    replicate n 'charHere'
    

    for example, if you want to repeat the char '-' 12 times:

    replicate 12 '-'
    
    0 讨论(0)
  • 2021-01-21 01:06

    Use replicate:

    underline :: String -> String
    underline = flip replicate '-' . length
    

    This will give you a string which is n times the character '-' where n is the length of the input string. It is the same as:

    underline = map $ const '-'
    

    You can then use it like this (if for example yourString = "Available Chars (111)"):

    > putStrLn yourString >> putStrLn (underline yourString)
    Available Chars (111)
    ---------------------
    
    0 讨论(0)
提交回复
热议问题