Skip to content

Instantly share code, notes, and snippets.

@rsslldnphy
Created June 24, 2014 15:51
Show Gist options
  • Save rsslldnphy/5dadf1bcf774cd1ba808 to your computer and use it in GitHub Desktop.
Save rsslldnphy/5dadf1bcf774cd1ba808 to your computer and use it in GitHub Desktop.
{-- | List the sub-sequences of conscutives elements in the list such that the
sum of the element is equal to the given number.
Examples:
>>> matchingSub 10 [1..5]
[[1,2,3,4]]
>>> matchingSub 2 $ replicate 3 1
[[1,1],[1,1]]
>>> take 2 $ matchingSub 2 $ repeat 1
[[1,1],[1,1]]
--}
import Data.Maybe(mapMaybe)
import Data.List(find, inits, tails)
matchingSub :: Int -> [Int] -> [[Int]]
matchingSub n = mapMaybe (find match . inits) . tails
where
match xs' = sum xs' == n
main :: IO ()
main = do
print $ matchingSub 10 [1..5]
print $ matchingSub 2 $ replicate 3 1
print $ take 2 $ matchingSub 2 $ repeat 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment