简体   繁体   English

是否有类似 Python 中的 Haskell 等效的可迭代解包方式?

[英]Is there a Haskell equivalent way of iterable unpacking like in Python?

I wonder if it is possible to create variables from an iterable of things in Haskell.我想知道是否可以从 Haskell 中的可迭代事物中创建变量。 I found this when I search for it but I couldn't adapt it for my case.我在搜索它时发现了这个,但我无法根据我的情况调整它。 Maybe it's not possible or I'm missing something since I'm a beginner.也许这是不可能的,或者因为我是初学者,所以我错过了一些东西。 Basically, I'm wondering if something like this is possible in Haskell:基本上,我想知道在 Haskell 中是否有可能:

>>> list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> a, b, c = list_of_lists
>>> print(a)
[1, 2, 3]
ghci> list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
ghci> [a,b,c] = list_of_lists
ghci> print a
[1,2,3]

The answer given by luqui works when the list has exactly three elements.当列表恰好包含三个元素时, luqui给出的答案有效。 It is, however, partial, which means that it'll fail at run-time for lists of any other size.然而,它是部分的,这意味着它在运行时对于任何其他大小的列表都会失败。

A more idiomatic Haskell solution, I think, would be a function like this:我认为,更惯用的 Haskell 解决方案将是这样的 function :

listToTriple :: [a] -> Maybe (a, a, a)
listToTriple [a, b, c] = Just (a, b, c)
listToTriple _ = Nothing

You can safely call it with lists of any length:您可以使用任意长度的列表安全地调用它:

*Q62157846> listToTriple [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Just ([1,2,3],[4,5,6],[7,8,9])
*Q62157846> listToTriple [[1, 2, 3], [4, 5, 6]]
Nothing
*Q62157846> listToTriple [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
Nothing

If, in the first case, you only want the first of those three lists, you can pattern-match on the triple:如果在第一种情况下,您只需要这三个列表中的第一个,则可以对三元组进行模式匹配:

*Q62157846> fmap (\(a, _, _) -> a) $ listToTriple [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Just [1,2,3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM