简体   繁体   English

Haskell 列表理解与元组输入

[英]Haskell list comprehension with tuple input

Is it possible to somehow use a tuple as input for a list comprehension?是否有可能以某种方式使用元组作为列表理解的输入? Or maybe a tuple comprehension?或者也许是元组理解? I expected the following to work, but it does not.我希望以下内容有效,但事实并非如此。

[x * 2 | x <- (4, 16, 32)]

I can not use lists from the very beginning as the given signature of my homework function is我不能从一开始就使用列表,因为我的作业功能的给定签名是

success :: (Int, Int, Int) -> Int -> (Int, Int, Int) -> Bool

But working with lists would be so much simpler as one part of the task requires me to count how many 1 s and 20 s there are in the tuples.但是使用列表会简单得多,因为任务的一部分需要我计算元组中有多少120

Control.Lens has overloaded traversal support for homogeneous tuples of all lengths: Control.Lens为所有长度的同构元组提供了超载的遍历支持:

import Control.Lens

-- Convert to list:
(3, 4, 5)^..each -- [3, 4, 5]
(1, 2)^..each -- [1, 2]

-- modify elements:
(4, 16, 32)& each %~ \x -> x * 2 -- (8, 32, 64)
(1, 2)& each %~ (+1) -- (2, 3)

-- operator notation for common modifications (see Control.Lens.Operators):
(1, 2, 3)& each +~ 2 -- (3, 4, 5)
(1, 2, 3)& each *~ 2 -- (2, 4, 6)

-- monadic traversals (here each works like `traverse` for the list monad)
each (\x -> [x, x + 1]) (1, 2) -- [(1,2),(1,3),(2,2),(2,3)]

-- `each` is basically an overloaded "kitchen sink" traversal for 
-- common containers. It also works on lists, vectors or maps, for example
[(3, 4), (5, 6)]& each . each +~ 1 -- [(4, 5), (6, 7)]

You could just create a function to convert a triple into a list:您可以创建一个函数将三元组转换为列表:

tripleToList :: (a, a, a) -> [a]
tripleToList (a, b, c) = [a, b, c]

then you can do那么你可以做

[x * 2 | x <- tripleToList (4, 16, 32)]

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

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