Sequential numbers in a list haskell

懵懂的女人 提交于 2019-12-31 07:38:11

问题


I am new to haskell and I was attempting a few coding problems that I previously completed for java, however the following problem has me stumped.

Basically the idea is to write a function that takes in a list of integers ([Int]) establishes whether a list of integers has consecutive 1's within it. For example the output of the following would be: Input: func [0,0,1,1,0] Output: True

A sample solution for this problem in haskell would be greatly appreciated, Thanks


回答1:


One way would be to use pattern matching to look for consecutive ones at the head of the list, and advance down the list until you find them, or you run out of elements to look at.

consecutiveOnes [] = False
consecutiveOnes (1:1:_) = True
consecutiveOnes (_:xs) = consecutiveOnes xs



回答2:


This is a solution:

consecutiveOnes :: [Int] -> Bool
consecutiveOnes xs = auxOnes False xs

auxOnes :: Bool -> [Int] -> Bool
auxOnes b [] = False
auxOnes b (x:xs) = case (x==1 && b) of {
    True -> True;
    False -> auxOnes (x==1) xs;
};

Another way would be using the isInfixOf method and asking if [1,1] appears anywhere on your list:

consecutiveOnes :: [Int] -> Bool
consecutiveOnes xs = isInfixOf [1,1] xs

The isInfixOf function takes two lists and returns True iff the first list is contained, wholly and intact, anywhere within the second.

But I'm sure there are many other ways of doing it.




回答3:


You could also do it this way:

consecutiveOnes [] = False
consecutiveOnes xs = any (== (1,1)) $ zip xs (tail xs)

If

 xs == [0,1,1,2,3,4]

Then

tail xs == [1,1,2,3,4]

Zipping them together you get a list of pairs, where each pair is an element of the list and the element after it.

zip xs (tail xs) == [(0,1),(1,1),(1,2),(2,3),(3,4)]


来源:https://stackoverflow.com/questions/43021548/sequential-numbers-in-a-list-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!