In today’s Programming Praxis exercise, our goal is to find four integers in a given list that sum up to a given target number. Let’s get started, shall we?
We use the same approach of storing pair sums as the given solution. We store them using the sum as the key, which means we can use an IntMap, which offers improved performance over a regular Map.
import qualified Data.IntMap as I
First we generate all the pairs, then we try to find two pairs that sum up to the given number.
sum4 :: Int -> [Int] -> [[Int]] sum4 n xs = take 1 [p1++p2 | (s, p1) <- I.assocs pairs , p2 <- maybe  return $ I.lookup (n-s) pairs] where pairs = I.fromList [(a+b, [a,b]) | a <- xs, b <- xs]
Some tests to see if everything is working properly:
main :: IO () main = do print $ sum (head $ sum4 0 [2,3,1,0,-4,-1]) == 0 print $ sum4 0 [1,2,3,4,5,6] ==  print $ sum4 13 [1,2,3,4,5,6] == [[1,1,6,5]]