user1709237
user1709237

Reputation:

How to convert a nested list of Chars to a String Haskell

I have a simple question, although Lists of Chars seem equivalent to Strings, they are not functionally working the same. if I have a nested List of Chars, of type [[Char]] that I would like to convert to a [String], how would I go about doing this?

When I try to perform a function on the [[Char]] and treat it as though it is a string I get:

Couldn't match expected type `([String] -> (Int, Int, Board)) -> t'
                with actual type `[[Char]]'

When I try to declare that type String = [[Char]] I get:

Ambiguous occurrence `String'
It could refer to either `Main.String', defined at Testing.hs:19:1
                      or `Prelude.String',
                         imported from `Prelude' at Testing.hs:16:1-14
                         (and originally defined in `GHC.Base')

Upvotes: 0

Views: 706

Answers (2)

Rein Henrichs
Rein Henrichs

Reputation: 15605

When I try to declare that type String = [[Char]] I get:

Ambiguous occurrence `String'
It could refer to either `Main.String', defined at Testing.hs:19:1
                      or `Prelude.String',
                         imported from `Prelude' at Testing.hs:16:1-14
                         (and originally defined in `GHC.Base')

You are getting this error because your definition of String conflicts with the one already defined in base and exported by the Prelude. Remove your definition and use the one that already exists instead.

Upvotes: 0

David Young
David Young

Reputation: 10793

Those two types are completely identical, because String is a type synonym for [Char]. The definition of String is

type String = [Char]

The type keyword means it's a type synonym. A type synonym is always interchangeable with the type it is defined to be.

You can see this in GHCi like this (note that Haskell does not allow casting):

ghci> let test :: [Char];   test = "abc"
ghci> test :: String
"abc"
ghci> :t (test :: [Char]) :: String
(test :: [Char]) :: String :: String

Upvotes: 1

Related Questions