I have the following code to return the length of a cycle in a string:
module Main where
import Data.List
detec ys n | 2*n > (length ys) = error "no cycle"
| t == h = (2*n - n)
| otherwise = detec ys (n+1)
where
t = ys !! n
h = if n == 0 then ys !! 1 else ys !! (n*2)
f x = detec (show x) 0
answer = map f [1/x|x<-[1..100]]
But what I don’t know how to do is make it ignore the "no cycle" exception so that the list produced only contains the lengths of the strings which are cyclic.
How can I do this?
Please don’t use
errorto implement logic where the “erroneous” result is expected to occur.Instead, why not return
Maybe ninstead of justn, then usecatMaybesto filter out theNothings?The changes are easy enough:
By the way, you’re indexing past the end of the list; perhaps you meant to check
2*n + 1 > length ys? Drifting slightly off topic, I’d like to mention that!!andlengthare, for the most part, both inefficient and non-idiomatic when applied to lists, especially in an iterating construct like this. The list type is basically a cons cell list, which is an intrinsically recursive data structure, and is emphatically not an array. Ideally you should avoid doing anything with a list that can’t be easily expressed with pattern matching, e.g.,f (x:xs) = ....