Op 31-10-2015 om 17:43 schreef Roelof Wobben:
Op 31-10-2015 om 14:56 schreef Roel van Dijk:
You are even closer now!

What the type checker is trying to tell you is that it doesn't know how to raise Maybe Integer to some power.

You apply the ^ operator to two values, f2Maybe (n `div` 2) and 2. Let us give them names:

let a = f2Maybe (n `div` 2) :: Maybe Integer
    b = 2 :: Int
in a ^ b

You see that the type of a is Maybe Integer. What does this mean? There are only 2 cases to consider. You have Just an integer or you have Nothing.

You can use the case construct to write the code for both cases.

f2Maybe :: Integer -> Maybe Integer
f2Maybe n
   | n > 0  = Nothing
   | n == 0  = Just 1
   | even n = case f2Maybe (n `div` 2) of
                Just x -> <fill in>
                Nothing -> <fill in>
   | odd n  = case f2Maybe (n `div` 2) of
                Just x -> <fill in>
                Nothing -> <fill in>



Still confusing.

with even you can have a integer which will be a integer or nothing if there is a number which is not even.
So with 1 it will be Nothing.

but will the odd even be reached ?


Roelof



Solved both ones like this :

f2Maybe :: Integer -> Maybe Integer
f2Maybe n
   | n < 0  = Nothing
   | otherwise = Just (f3 n )
 
f3 :: Integer -> Integer
f3 n 
  | n == 0  = 1
  | even n = f3 ( n `div` 2) ^ 2
  | odd n  = (f3 ( n `div` 2) ^ 2) * 2 


f2Either :: Integer -> Either String Integer
f2Either n
  | n < 0      = Left "This function works only with positive number"
  | otherwise  = Right (f3 n) 

So I can now test on Nothing or Left "This function works only with positive number" ?

Roelof