You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell中将字符串转换为嵌套列表的方法咨询

Converting String Representations of Nested Lists to Actual Haskell Lists

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 read is 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 readMaybe from the Text.Read module instead of read. It returns a Maybe value (either Just the parsed list or Nothing if 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:37:20