Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for consecutive True in list Haskell using fold

Tags:

haskell

I'm new to Haskell.

For a Project Euler problem, I've generated a list of bools.

[True, False, False, True, False. . .True]

What I'd like is to write a function find the first four consecutive True's, then return their indices in the list.

Intuitively, I know I should be doing this with a fold and somehow pattern matching. Could you help me? Something like this with a fold? (I have no idea how to retrieve the index of an element.)

consecutiveFourTrues (w:x:y:z):xs = if (w && x && y && z) then w else consecutiveFourTrues (x:y:z):xs

Thank you for your help!


1 Answers

tldr

findIndices (\x -> (x == True)) $ map (\x -> all (== True) x) $ sliding 2 bs

Define a sliding function similar to the one found in Scala.

sliding :: Int -> [a] -> [[a]]
sliding size [] = []
sliding size ls@(x:xs) = if length ls >= size then (take size ls) : sliding size xs else sliding size xs

Using sliding 2 with [True, False, False, True, True, False, True, False, True, True] gives

[[True,False],[False,False],[False,True],[True,True],[True,False],[False,True],[True,False],[False,True],[True,True]]

Then we can map to see if each sub list is contains all True values and get the indices of those that do with findIndices.

findIndices (\x -> (x == True)) $ map (\x -> all (== True) x) $ sliding 2 bs

[3,8]

like image 156
Brian Avatar answered Apr 18 '26 08:04

Brian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!