Char to string function

爱⌒轻易说出口 提交于 2020-01-21 06:08:32

问题


I have a very simple question: Given a function accepting a char and returning a string

test :: Char -> [String]

how can one convert the char into a string? I'm confused over the two types.


回答1:


In Haskell String is an alias for [Char]:

type String = [Char]

If you just want a function that converts a single char to a string you could e.g. do

charToString :: Char -> String
charToString c = [c]

If you prefer pointfree style you could also write

charToString :: Char -> String
charToString = (:[])



回答2:


A String is just a [Char]

But that's just a nice way of saying

'H':'E':'L':'L':'O':[]

So to make it a [String] we could do:

['H':'E':'L':'L':'O':[]]



回答3:


Another way would be using

return . return

Since return for lists is defined as :[]




回答4:


Note that you can convert any type implementing the Show type class to a string using show:

(Show a) => a -> String

Because Char implements this, the function is already written for you!



来源:https://stackoverflow.com/questions/6168739/char-to-string-function

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