I am new to Haskell/FP. I want to solve this task:
This list is given: [1721, 979, 366, 299, 675, 1456]
Find the two elements that sum to 2020
and multiply them. The solution is 1721 * 299.
I think in Haskell, the tools I can use to solve this problem are list comprehension and fold (or a combination of them). But I don't understand how I can write a list comprehension that takes into account other elements of the same list, and not just one element at the time.
This is what I came up with after several hours (ints
is the list):
print [(x,y, x*y) | x <- ints, y <- ints, x+y == 2020]
It actually prints the right answer. But I think my solution is dirty:
- I feed the input list twice into the list comprehension. Is this correct? It seems like overhead/duplication to me. I am sure there is a better way.
- The return of the function is a list with two same entities (I assume this is because of what I described in the last bullet):
[(1721,608,514579),(1721,608,514579)]
- of course I could get a single element with head
, but that doesn't solve the root of the problem.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…