DEV Community

Discussion on: Daily Challenge #63- Two Sum

Collapse
 
craigmc08 profile image
Craig McIlwrath

Haskell:

import Control.Applicative
import Data.List (find) 

twoSum :: (Eq a, Num a) => [a] -> a -> Maybe (Int, Int) 
twoSum xs target = let withId = zip xs [0..]
                       sums = (\(x,a) (y,b) -> (x+y, (a, b))) <$> withId <*> withId
                   in find ((==target) . fst) sums >>= (return . snd)

I know the question said the input is always good, but I didn't want to ignore possible errors in when using the function...

I'm not sure of the speed of this code either. My guess is it only evaluates combinations until it finds a correct one? But I'm not an expert on lazy evaluation and I'm pretty sure this could be faster.