Haskell中将字符串转换为嵌套列表的方法咨询
Great question! In Haskell, you absolutely can turn those stringified nested lists into real, usable Haskell lists—no custom parsing needed for most cases, thanks to the language's built-in type classes.
The Straightforward Solution: read
The read function is your go-to here. It leverages the Read type class, which has default implementations for lists and basic numeric types like Int. All you need to do is make sure your string matches valid Haskell list syntax (which your examples already do!) and specify the target type so Haskell knows what to parse into.
Example 1: 2-Level Nested List
-- Parse the simple nested list string let input = "[ [1,1] , [2,2] ]" let result = read input :: [[Int]] -- result is now the actual list [[1,1], [2,2]]
Example 2: 3-Level Nested List
For your more complex example, just adjust the type annotation to match the nesting depth:
let complexInput = "[ [ [1,1], [1,1] ], [ [2,2] , [2,2] ] , [ [1,1] ,[1,1] ] ]" let complexResult = read complexInput :: [[[Int]]] -- complexResult is the 3-level nested list you need
Important Notes
- Type Annotations Are Mandatory: Since
readis polymorphic, Haskell can't infer the target type on its own. You need to add a type like[[Int]]or[[[Int]]]to tell it exactly what structure to parse. - Syntax Must Be Valid: Your string needs to follow Haskell's list rules properly—matching square brackets, commas between elements, and valid literals. Extra spaces (like in your examples) are totally fine.
- Safe Parsing for Unreliable Input: If your input might have formatting errors (like missing brackets or invalid numbers), use
readMaybefrom theText.Readmodule instead ofread. It returns aMaybevalue (eitherJustthe parsed list orNothingif parsing fails) instead of crashing your program:
import Text.Read (readMaybe) -- A safe parser for 3-level nested Int lists safeNestedParse :: String -> Maybe [[[Int]]] safeNestedParse = readMaybe -- Usage examples safeNestedParse "[ [ [1,1], [1,1] ], [ [2,2] , [2,2] ] ]" -- Just [[[1,1],[1,1]],[[2,2],[2,2]]] safeNestedParse "[ [1,1], [2,2" -- Nothing (missing closing bracket)
That's all you need! For most cases where your input is well-formed, read will handle the nested structure perfectly.
内容的提问来源于stack exchange,提问作者Julio CMC

