Reputation: 5086
I have the following function:
followConnections :: [Connection]->Crib->Stecker->Offsets->Maybe Stecker
followConnections [] _ y _ = Just (y)
followConnections w x y z
| fC /= Nothing = trace("Follow Connections recursing") followConnections (tail w) x (fromMaybe(fC)) z
| fC == Nothing = trace("Follow connections fail! for " ++ show y) Nothing
where
fC = followConnection (head w) x y z
Technically, the function should recurse if the current element of [Connection]
does not cause followConnection
to return Nothing
, or return Nothing
otherwise.
However, by tracing the function I saw that it will recurse until [Connection]
is empty even at some point it fails.
Any idea of why this may be??
Thanks!
Upvotes: 0
Views: 128
Reputation: 47382
It makes a lot more sense to write your function using pattern matching and a case statement, which avoids all the calls to fromMaybe
, head
and tail
that are currently cluttering up your code.
followConnections :: [Connection] -> Crib -> Stecker -> Offsets -> Maybe Stecker
followConnections [] _ y _ = Just y
followConnections (w:ws) x y z = case fC of
Nothing -> trace ("Fail! for " ++ show y) $ Nothing
Just y' -> trace ("Recursing") $ followConnections ws x y' z
where
fC = followConnection w x y z
Since x
and z
are fixed in the recursion, it also makes sense to write this using a helper function
followConnections ws x y z = go ws y
where
go [] y = Just y
go (w:ws) y = case fc of
Nothing -> trace ("Fail for" ++ show y) $ Nothing
Just y' -> trace ("Recursing") $ go ws y'
where
fc = followConnection w x y z
Finally, you could use the function maybe
from Data.Maybe
to get rid of the case
statement, simplifying the code even further.
followConnections ws x y z = go ws y
where
go [] y = Just y
go (w:ws) y = maybe Nothing (go ws) (followConnection w x y z)
Now that the function is simplified, it should be a lot easier to work out where it is going wrong.
Upvotes: 2