Hi all. I'm experimenting with haskell and its type system. I've done a function which scans a list, and returns "Just a" value if the element is found, or Nothing. get :: a -> Maybe a and implemented getAorB :: Maybe a -> Maybe a -> a getAorB a b = ... a function which returns "Just (get a)" or "Just (get b)" if (get a) is Nothing (excluding failures in both). By now, I've implemented it in terms of pattern matching: getAorB a b = f (get a) (get b) where f (Just a) Nothing = a f Nothing (Just a) = a but I'd like to know if there are other possible ways to do it, possibly without enforcing an evaluation order like pattern matching does.
The problem with your approach is that getAorB does not halt if the list does not contain the first element. For example:
getAorB 6 5 [5,5..]
While you may not care about a contrived example like this, it does imply that your function scans the list once, searching for the first element, and once again, searching for the second. Note that it scans twice even if the first element was found, because of the pattern:
f (Just a) Nothing = a f Nothing (Just a) = a
The following pattern behaves better:
f (Just a) _ = a f _ (Just a) = a
and halts on:
getAorB 5 6 [5,5..]
I don't think there is a way to get proper laziness by using get twice. I suggest implementing getAorB using explicit recursion, which is probably how you implemented get. -Arjun
participants (2)
-
Arjun Guha -
Yuri D'Elia