简体   繁体   中英

String and add special characters from a list in Haskell

In Haskell I used to use filter to strip set of numbers from a list. However, I have not been able to make it working with this particular case.

I have a list of strings as follow:

["A","B","C","D","E","F","A","B","N"]

I want to string the [] and "" so the final string is (with spaces):

A B C D E F A B N

shouldn't a simple filter like print filter([) ["A","B","C","D","E","F","A","B","N"] remove the [ ?

update:

I read over this document and was able to get the following result:

let example = (concat (intersperse " " ["A","B","C","D","E","F","A","B","N"]))
print example
-- this prints "A B C D E F A B N"

However, when I use this :

-- where createalphs create a list of strings
-- and userinput is a string entered by the user 

let setofalph = ($ createalphs $ words userinput)
let example = (concat (intersperse " " setofalph))
print example

I get this error

Couldn't match expected type `[[Char]]'
In the second argument of `intersperse', namely `setofalph'
In the first argument of `concat', namely
  `(intersperse " " setofalph)'
In the expression: (concat (intersperse " " setofalph))

unwords works fine:

λ> unwords ["A","B","C","D","E","F","A","B","N"]
"A B C D E F A B N"

Additionally, Data.List.intersperse would help, along with concat .

import Data.List

solution :: [String] -> String
solution =  concat . intersperse " "

What this does is separate each value in the list with " " , then join (concatenate) the lists together.

If you want to separate with ", " , you can easily change the above function:

solution :: [String] -> String
solution =  concat . intersperse ", "

so that:

λ> solution ["A","B","C","D","E","F","A","B","N"]
"A, B, C, D, E, F, A, B, N"
λ> putStrLn $ solution ["A","B","C","D","E","F","A","B","N"]
A, B, C, D, E, F, A, B, N

To put this into the context of your IO:

main = do
  x <- getLine
  putStrLn $ solution $ createalphs $ words x

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