[Haskell-cafe] Maybe won't let me count
Galaxy Being
borgauf at gmail.com
Mon Mar 29 03:12:07 UTC 2021
I've got this
import Data.Maybe
data MyList a = Empty | Cons a (MyList a) deriving (Eq,Ord,Show)
data BaconOrIndex = Bacon | Indx Int deriving (Eq,Ord,Show)
whereIsBM Empty = Nothing
whereIsBM (Cons idx lx) = if (idx == Bacon) then Just 1 else (whereIsBM lx)
which I would like to tell me where the Bacon is (index), not just if
there's Bacon, which is what it does now. That is, I need this to happen
> whereIsBM (Cons (Indx 5) (Cons Bacon (Cons (Indx 2) (Cons (Indx 8)
Empty))))
Just 2
So I need to traverse a BaconOrIndex list and count how deep I went to find
the Bacon variable. I get the above code to evaluate error-free, but
obviously I'm only returning a Just 1 when it sees Bacon. What I need is to
have the last part be
. . . else (1 + whereIsBM lx)
work; but it keeps giving the error
Non type-variable argument in the constraint: Num (Maybe a)
(Use FlexibleContexts to permit this)
• When checking the inferred type
whereIsBM :: forall a.
(Num a, Num (Maybe a)) =>
MyList BaconOrIndex -> Maybe a
I haven't a clue what this means. Eventually, I'll wrap this in something
that handles the Nothing and does fromJust on the alternative. This whole
effort is because if I didn't use the Maybe strategy, and said
whereIsBM Empty = 0
...
it would never give back 0 if it didn't find Bacon, rather, it would simply
return the whole countdown to Empty. What can I do to make Maybe work here?
LB
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20210328/1c9a9151/attachment.html>
More information about the Haskell-Cafe
mailing list