Julio CMC
Julio CMC

Reputation: 33

Haskell Convert String to nested lists

I have a doubt, is there a function in haskell that can help me solve this? I'm trying to receive as an input a String with the form of a list and the convert it into an actual list in haskell

for example:

convert "[ [1,1] , [2,2] ]" into [ [1,1] , [2,2] ]

Example 2:

convert "[ [ [1,1], [1,1] ], [ [2,2] , [2,2] ] , [ [1,1] ,[1,1] ] ]"

into [ [ [1,1], [1,1] ], [ [2,2] , [2,2] ] , [ [1,1] ,[1,1] ] ]

thanks in advance!

Upvotes: 2

Views: 230

Answers (2)

Haleemur Ali
Haleemur Ali

Reputation: 28313

One option could be to use the Aeson package and treat the text as json data.

Prelude> :set -XOverloadedStings
Prelude> import Data.Aeson
Prelude Data.Aeson> jsString = "[ [ [1,1], [1,1] ], [ [2,2] , [2,2] ] , [ [1,1] ,[1,1] ] ]"
Prelude Data.Aeson> decode jsString :: Maybe [[[Int]]]
Just [[[1,1],[1,1]],[[2,2],[2,2]],[[1,1],[1,1]]]

Upvotes: 1

Michiel Borkent
Michiel Borkent

Reputation: 34860

Yes, that function is read. If you specify what it should read in a type annotation, you will get the desired result, provided there is an instance of Read for that type.

read "[ [1,1] , [2,2] ]" :: [[Int]]
-- [[1,1],[2,2]]

read "[ [ [1,1], [1,1] ], [ [2,2] , [2,2] ] , [ [1,1] ,[1,1] ] ]" :: [[[Int]]]
-- [[[1,1],[1,1]],[[2,2],[2,2]],[[1,1],[1,1]]]

Upvotes: 8

Related Questions