Skip to content

Instantly share code, notes, and snippets.

@geowa4
Last active December 11, 2015 21:18
Show Gist options
  • Save geowa4/4661209 to your computer and use it in GitHub Desktop.
Save geowa4/4661209 to your computer and use it in GitHub Desktop.
Count the number of pairs in `nums` that total `target`. Sort is performed at the very beginning to allow for some assumptions to be made in the recursive routine. I want to figure out how to remove the sort; it wouldn't be needed in the declarative version.
import Data.List
countPairs :: (Integral a, Num b) => [a] -> a -> b
countPairs nums target = counter (sort nums) target
where
counter :: (Integral a, Num b) => [a] -> a -> b
counter [] _ = 0
counter [_] _ = 0
counter sn t
| s == t = 1 + counter (init (tail sn)) t
| s < t = counter (tail sn) t
| otherwise = counter (init sn) t
where
s = head sn + last sn
-- countPairs [1,2,5,8,9] 10 == 2
-- countPairs [1,9,1,8,1,2,9] 10 == 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment