[Solved] Haskell: Given a list of numbers and a number k, return whether any two numbers from the list add up to k


There are following approaches.

1) Create a list pf pairs which are all combinations [(10,10),(10,15),..,(15,10),(15,3)..].
Now you can use simple any function on this list to check if any pair add up to given number.

getCoupleList :: [a]->[(a,a)]
getCoupleList [] = []
getCoupleList [x] = []
getCoupleList (x:xs) = map (\y->(x,y)) xs ++ getCoupleList xs

getSumOfCoupleList :: Num a => [(a,a)]->[a]
getSumOfCoupleList xs = map (\x -> fst x + snd x) xs 

isSum :: [Int]->Int->Bool
isSum xs k = any (==k) $ (getSumOfCoupleList.getCoupleList) xs

or directly check wuthout getSumOfCoupleList

isSum xs k = any (\(a,b)-> a + b == k) $ (getSumOfCoupleList.getCoupleList) xs

If you check creating the couple list and finding the sum in not needed. We can directly get the list of sum with simple changes.

getSumList :: Num a=>[a]->[a]
getSumList [] = []
getSumList [x] = []
getSumList (x:xs) = map (+x) xs ++ getSumList xs

isSum1 :: [Int]->Int->Bool
isSum1 xs k = any (==k) $ getSumList xs 

2) Create another list from given list by subtracting every element from 17. Now just check if any number from first list is present in second.

isSum2 :: [Int]->Int->Bool 
isSum2 xs k = let newList = map (k-) xs
                  intersectList = xs `intersect` newList
                  in not (null intersectList)

solved Haskell: Given a list of numbers and a number k, return whether any two numbers from the list add up to k