How to print the same char n times in Haskell

▼魔方 西西 提交于 2021-01-20 08:12:09

问题


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)" and I want to have a char underlining that sentence, which should have exactly the same length as the "Available Chars (x)". But x is an int, so it could be "1" or "10" or "1000" etc.. so the length is variable. I got the length but i didnt know how to print that char as long as the string is...


回答1:


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



回答2:


got it!

replicate n 'charHere'

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

replicate 12 '-'



回答3:


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) 


来源:https://stackoverflow.com/questions/26618059/how-to-print-the-same-char-n-times-in-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!