Using partial functions (functions that may not return a value) is usually not recommended. Functions such as head and fromJust exist because they are sometimes convenient; you can sometimes write shorter code, which is more understandable to students. Many functional algorithms are expressed through head and tail , and fromJust conceptually matches head .
It is usually preferable to use pattern matching and avoid partial functions, as this allows the compiler to catch errors for you. In your code fragment, you carefully checked that the value is never Nothing , but in large real code files the code can be many years, 1000 lines are long and are supported by many developers. It is very easy for a developer to override the code and skip such a check. When matching with a pattern, it is located directly in the code structure, and not just in any arbitrary Bool expression.
It's not so difficult to replace using fromJust template:
answer26 = answer26' 1000 answer26' n = snd $ maximum $ map (\x -> cycleLength x [1]) [2..n - 1] where cycleLength n (r:rs) = case elemIndex r rs of Just i -> (1 + i, n) Nothing -> if r < n then cycleLength n $ (10*r):r:rs else cycleLength n $ (r `mod` n):r:rs
And (I think) the result is also more clear.
Edit: There seems to be a “theoretically good” place to use fromJust mentioned in Typeclassopedia , although you will need someone other than me to explain wtf what everything is about ..;)
source share