-2

I am still not into Haskell and need a hint for the following function.

I want to create a list by adding each multiplication of a pair:

all :: Int -> (Int,Int) -> [(Int, Int)] 
all n, pair = ...

E.g. n = 3, pair (1,2) => [(1,2), (2,4), (3,6)] which expands to [(1*(1,2)), ((2*(1,2)), (3*(1,2))]

I know its something with x <- [1..n] and x*pair but I don't know which built-in function is right to put it together!

Redu
  • 25,060
  • 6
  • 56
  • 76
Tim4497
  • 340
  • 3
  • 19

1 Answers1

4

You need to do the multiplication separately on the elements in the tuples, and then recreate a tuple. You can use fst and snd to get the elements.

all n pair = [(x*(fst pair), x*(snd pair)) | x <- [1..n]]

Pattern matching is another common way to access tuple elements.

all n (a, b) = [(x*a, x*b) | x <- [1..n]]
Daniel Wagner
  • 145,880
  • 9
  • 220
  • 380
ShamPooSham
  • 2,301
  • 2
  • 19
  • 28
  • 1
    Just for curiosity, there are other ways to map to a tuple: https://stackoverflow.com/questions/9722689/haskell-how-to-map-a-tuple – Lorenzo Feb 10 '20 at 22:36
  • @Lorenzo That's true, thanks for pointing it out. `both` from the extra package seems to do it. But I think it's good practice for beginners to solve this themselves. – ShamPooSham Feb 10 '20 at 22:40
  • 1
    it's much nicer (imo, but pretty sure almost every Haskell developer would agree) to pattern match on the pair rather than using `fst` and `snd` – Robin Zigmond Feb 10 '20 at 22:48