[Haskell-beginners] Maybe problems converting back to number

Galaxy Being borgauf at gmail.com
Sun Mar 7 04:17:26 UTC 2021


Here's what I finally did

myIndex'' l n
  | m == Nothing = error "No list."
  | otherwise = fromJust m
      where m = mI l n
            mI [] _ = Nothing
            mI (h:t) n | n == 0 = Just h
                   | otherwise = mI t (n-1)

but then I can't say why I went to this extra step.



On Sat, Mar 6, 2021 at 10:53 AM Francesco Ariis <fa-ml at ariis.it> wrote:

> Il 06 marzo 2021 alle 09:53 Galaxy Being ha scritto:
> > I've got this example from the Internet
> >
> > import Data.List
> > import Data.Maybe
> >
> > firstFactorOf x
> >     | m == Nothing = x
> >     | otherwise = fromJust m
> >     where m =(find p [2..x-1])
> >           p y = mod x y == 0
> >
> > -- myIndex :: [a] -> Int -> Maybe a
> > myIndex [] _ = Nothing
> > myIndex (x:xs) 0 = Just x
> > myIndex (x:xs) n = myIndex xs (n-1)
> >
> > I would like the Just x in the second block to actually be fromJust x as
> in
> > the first block, i.e., I want a number returned, not a Just typed object.
> > I've tried changing Just x to fromJust x but get the error when I try to
> > use it
>
> What would happen in the `Nothing` case? If an error is fine with you:
>
>     myUnsafeIndex :: [a] -> Int -> a
>     myUnsafeIndex as n =
>             case myIndex as n of
>               Nothing -> error "Chiare, fresche et dolci acque"
>                          -- or maybe return -1? Idk
>               Just r -> r
>
> What have you written instead
>
> > Also, my type declaration seems to be wrong too, but I don't see why.
>
> It compiles fine here, even if I remove the comment from `myIndex`
> signature
> —F
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20210306/c946bd5c/attachment.html>


More information about the Beginners mailing list