开发者

Char to string function

开发者 https://www.devze.com 2023-03-09 15:22 出处:网络
I have a very simple question: Given a function accepting a char and returning a string test :: Char -> [String]

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

test :: Char -> [String]
开发者_JAVA技巧

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


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 = (:[])


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':[]]


Another way would be using

return . return

Since return for lists is defined as :[]


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号