Skipping exceptions when using map in Haskell

dictionary, error-handling, haskell

Solution

Please don't use `error` to implement logic where the "erroneous" result is expected to occur.

Instead, why not return `Maybe n` instead of just `n`, then use `catMaybes` to filter out the `Nothing`s?

The changes are easy enough:

module Main where
import Data.List
import Data.Maybe

detec ys n | 2*n > (length ys) = Nothing
           | t == h = Just (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 = catMaybes $ map f [1/x|x<-[1..100]]

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 `!!` and `length` are, 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) = ...`.

Problem

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?

Original source