MondayMorningHaskell / haskellings

An automated tutorial to teach you about Haskell!
BSD 3-Clause "New" or "Revised" License
166 stars 25 forks source link

Monads1.hs / addAndNegate3 #49

Closed damien-biasotto closed 3 years ago

damien-biasotto commented 3 years ago

Hi there,

I'm having trouble understanding the expected value for the test case addAndNegate3:

My code is the following:

addAndNegate xs = (+) <$> [1,2,3] <*> xs >>= \x -> [x,-x]

TestCase addAndNegate3: addAndNegate [1, 2] @?= [2, -2, 3, -3, 4, -4, 3, -3, 4, -4, 5, -5]

I would have expected the value to be instead [2, -2, 3, -3, 3, -3, 4, -4, 4, -4, 5, -5]since we apply the input one by one and in the order of the list: 1 + 1: 2, -2, 1+2: 3, -3, 2+1: 3, -3, 2+2: 4, -4, 1+3: 4, -4, 2+3: 5, -5

Am I misunderstanding the description of the function or is the expected value incorrect?

damien-biasotto commented 3 years ago

I'm even more confused, the code I wrote using the do notation works fine. And I believe I'm wrong but it is fairly similar that the one liner I wrote above:

addAndNegate xs = do
  x <- xs
  y <- [1,2,3]
  [x + y, -(x+y)]
damien-biasotto commented 3 years ago

Oh! I think I know what's the difference. my one-liner is actually applying [1,2,3] to the input whereas in the do notation I apply the input to [1,2,3].

The one-liner should be like this instead: addAndNegate xs = (+) <$> xs <*> [1,2,3] >>= \x -> [x,-x]