在 Haskell 中无法实现您想要做的事情,因为值 [[3, [3, 5], [5, 4]], [4, [1, 9], [2, 3]] 的类型无效。那里甚至没有足够的右括号,你少了一个。 [3, [3, 5]] 的类型是什么? [[Int]]? [Int]?都不合适。
即使你的例子是错误的:
> map read ["3", "2", "1"] :: [[Int]]
[*** Exception: Prelude.read: no parse
因为[3, 2, 1] 的类型为[Int],而不是[[Int]]。请记住,这不是 Python,列表只能包含单一类型的元素。
相反,如果您有类似["3", "[3,5]", "[5,3]"] 的输入,您可以使用类似的内容对其进行解析
import Text.Read (readMaybe)
readEither :: (Read a, Read b) => String -> Maybe (Either a b)
readEither s = case readMaybe s of
Just x -> Just $ Left x
Nothing -> case readMaybe s of
Just y -> Just $ Right y
Nothing -> Nothing
这可以更短地表达,但我认为这很好地表达了这一点。然后您可以使用它来解析您的值:
parseMyList :: [String] -> [Maybe (Either Int [Int])]
parseMyList = map readEither
并将其用作
> parseMyList ["3", "[3,5]", "[5,3"] -- Incomplete last element!
[Just (Left 3), Just (Right [3,5]), Nothing]
我在那里留下了一个意外的错字,所以你可以看到它也优雅地失败了。
可以使用Monoid编写更短的实现:
import Text.Read (readMaybe)
import Data.Monoid
readEither :: (Read a, Read b) => String -> Maybe (Either a b)
readEither = getFirst $ mconcat $ map First [fmap Left $ readMaybe s, fmap Right $ readMaybe s]
也许有人可以打更多的高尔夫球。