Reputation: 16860
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.
Upvotes: 0
Views: 583
Reputation: 30103
Control.Lens
has overloaded traversal support for homogeneous tuples of all lengths:
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)]
Upvotes: 5
Reputation: 144126
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)]
Upvotes: 2