Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 281
Julio CMC Avatar asked Jul 25 '26 01:07

Julio CMC


2 Answers

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]]]
like image 91
Michiel Borkent Avatar answered Jul 28 '26 13:07

Michiel Borkent


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]]]
like image 25
Haleemur Ali Avatar answered Jul 28 '26 14:07

Haleemur Ali