Can you write a haskell function that solves the two sum problem, where the inputs are a…
- User
Can you write a haskell function that solves the two sum problem, where the inputs are a vector of numbers and a target number. The function should return the two numbers in the array that some to the target number or return -1 if an answer is not found in the array
Assistant
Here is a Haskell function to solve the two sum problem:
twoSum :: (Num a, Eq a) => [a] -> a -> (a, a) twoSum nums target = go nums Set.empty where go [] _ = (-1, -1) go (x:xs) seen | target - x `Set.member` seen = (x, target - x) | otherwise = go xs (Set.insert x seen)The key steps:
- Use a Set to track numbers we've seen so far
- Iterate through the list, at each step:
- Check if target - current number is in the Set
- If so, return the current number and target - current number
- Otherwise, add current number to Set and recur on rest of list
- Return (-1,-1) if no match found after iterating through full list
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.