简体   繁体   中英

Haskell: Print Int from list one by one

I've got a short question regarding something I want to do in Haskell. What I basically aim to achieve is to make a list of integers from 1 to a specific value y. Like [1..y], and the print this list with spaces between each number

Let's say i have [1..8]

My desired output is ("_" represents spaces):

_1_2_3_4_5_6_7_8

I have played a little bit with different things but without any luck

This is basically what Iv' got so far

printLst :: [Int] -> String
printLst (x:xs) = " " ++ putStr (show x) >> printLst xs

I've been searching around the web to find any solution to this, but I have not found anything that helps me do this.

Help is greatly appreciated

First, define a function which converts an Int to a String , then prepends a space to the result.

\x -> ' ' : show x

Now map this over your list:

>  map (\x -> ' ' : show x) [1..8]
[" 1"," 2"," 3"," 4"," 5"," 6"," 7"," 8"]

Now we just need to concatenate all the strings into one:

> concat (map (\x -> ' ' : show x) [1..8])
" 1 2 3 4 5 6 7 8"

This can be simplied using the concatMap function:

> concatMap (\x -> ' ':show x) [1..8]
" 1 2 3 4 5 6 7 8"

which forms the basis for the Monad instance for lists:

> [1..8] >>= (\x -> ' ' : show x)
" 1 2 3 4 5 6 7 8"

or even more briefly, using function composition

> [1..8] >>= (' ' :) . show
" 1 2 3 4 5 6 7 8"

Once you have the final string, now you can worry about printing it.

> putStrLn $ [1..8] >>= (' ' :) . show
 1 2 3 4 5 6 7 8

Well you are confusing things here, first of all:

putStr :: String -> IO ()

And you are returning a String , so no need to use that. Also, you have no patter for [] and singleton list, you can add them to get a better output like this:

printLst :: [Int] -> String
printLst [] = ""
printLst [x] = (show x)
printLst (x:xs) = (show x) ++ " " ++ printLst xs

If you want to use IO () function, use it in the main function:

main = do
  putStrLn (printLst [1..8])

This is a list processing problem. For an empty list, we can return the empty string, for a non-empty list, we can first yield a space, followed by the show of that item, and then recurse on the rest of that list, like:

prefixSpace :: Show a => [a] -> String
prefixSpace [] = ""
prefixSpace (x:xs) = ' ' : show x ++ prefixSpace xs

Or as a "fold" pattern:

prefixSpace :: Show a => [a] -> String
prefixSpace = foldr (\x -> ((' ' : show x) ++)) ""

This will not print the string. For that you need putStrLn:: String -> IO () , but as the signature indicates, if you putStrLn some_string , you work with an IO () .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM