Reputation: 89
Is there any way to convert an input string directly to a list?
The input string is already in the form of a list e.g.:
[((1,2),x),((3,2),y)]
I just want to convert it to [((1,2),x),((3,2),y)]
which can be used in another function without having to through the string to get all the values and then make an identical list.
Is this possible?
Upvotes: 3
Views: 599
Reputation: 2703
As mentioned, you can use read
to convert your String
into a value of type [((Int, Int), Animal)]
, provided Animal
is an instance of Read
. The instance can be derived automatically:
data Animal = Dog | Cat deriving (Show, Read)
Another potential pitfall is that you should specify the type annotation explicitly so read
knows what to parse for:
main :: IO ()
main =
do let list = read "[((1,2),Dog),((3,2),Cat)]" :: [((Int, Int), Animal)]
animals = map snd list
print animals
The output:
$ runhaskell test.hs
[Dog,Cat]
Upvotes: 2
Reputation: 530853
You just need to define a Read
instance for your type.
> data Animal = Dog | Cat deriving (Read, Show)
> read "[((1,2),Dog),((3,2),Cat)]" :: [((Int, Int), Animal)]
[((1,2),Dog),((3,2),Cat)]
Upvotes: 3