[Haskell-beginners] Maybe problems converting back to number
Francesco Ariis
fa-ml at ariis.it
Sat Mar 6 16:52:16 UTC 2021
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
More information about the Beginners
mailing list