No instance for (Num Bool) arising from the literal ‘0’ - haskell

My code:
divisibleBy :: Int -> Int -> Bool
divisibleBy x y
| mod x y == 0 = True
| otherwise = False
isEven :: Int -> Bool
isEven x
| (divisibleBy x 2) == 0 = True
| otherwise = False
Error:
practical1.hs:30:28: error:
• No instance for (Num Bool) arising from the literal ‘0’
• In the second argument of ‘(==)’, namely ‘0’
In the expression: (divisibleBy x 2) == 0
In a stmt of a pattern guard for
an equation for ‘isEven’:
(divisibleBy x 2) == 0
|
30 | | (divisibleBy x 2) == 0 = True |
The divisibleBy function works, but the isEven one doesn't. What am I doing wrong?

Well the error message already says this. You write:
isEven :: Int -> Bool
isEven x
| (divisibleBy x 2) == 0 = True
| otherwise = False
Now if we typecheck this, we see that (divisibleBy x 2) will return a Bool, and you cannot perform a (==) with a Bool and a number (a Bool is in Haskell not a number).
Why you write this with == 0 is not really clear for me, we can write it as:
isEven :: Int -> Bool
isEven x
| (divisibleBy x 2) = True
| otherwise = False
But now it is still inelegant: we do not have to check if a condition holds to return True and otherwise False, we can simply return the definition, so:
isEven :: Int -> Bool
isEven x = divisibleBy x 2
Or we can omit the x parameter, by using flip :: (a -> b -> c) -> b -> a -> c:
isEven :: Int -> Bool
isEven = flip divisibleBy 2
The same holds for the divisibleBy function, we can rewrite it to:
divisibleBy :: Int -> Int -> Bool
divisibleBy x y = mod x y == 0
Or without parameters:
divisibleBy :: Int -> Int -> Bool
divisibleBy = ((0 ==) .) . mod
Swapping the parameters of divisableBy
It looks however more Haskell to swap the parameters of the function, so we can write it as:
divisibleBy :: Int -> Int -> Bool
divisibleBy x y = mod y x == 0
Since now we can define a function divisibleBy 2, that will check for any parameter whether that number is divisible by two.
In that case, the isEven function, looks like:
isEven :: Int -> Bool
isEven = divisibleBy 2

Related

Syntax for partial function composition

module Luhn (isValid) where
import qualified Data.Char as C
isAsciiAlpha :: Char -> Bool
isAsciiAlpha = C.isAsciiLower || C.isAsciiUpper
isValid :: String -> Bool
isValid n
| any ((isAsciiAlpha || C.isSpace) . not) n = False
| otherwise = ys > 1 && sum xxs `mod` 10 == 0
where
xs = reverse [c | c <- n, isAsciiAlpha c]
ys = length xs
zs = zip xs (cycle [1, 2])
xxs = [convert x y | (x, y) <- zs]
convert :: Char -> Int -> Int
convert c mul =
do
let n = C.digitToInt c
case () of
_
| mul == 2 && (n > 4) -> n * mul - 9
| otherwise -> n * mul
I'm struggling with this line: any ((isAsciiAlpha || C.isSpace) . not) n = False. What I want is pretty obvious; find if any of the characters is something other than an ASCII alphabet or a space.
In spite of trying various syntaxes, I keep getting compilation error on this line, something like
• Couldn't match expected type ‘Bool’
with actual type ‘Char -> Bool’
You can not use (||) :: Bool -> Bool -> Bool on two functions: the parameters should be both Bools. What you can do is construct a function that maps a character c on isAsciiAlpha c || C.isSpace c, so \c -> isAsciiAlpha c || C.isSpace c, or you can use liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c with liftA2 (||) isAsciiAlpha C.isSpace. The not :: Bool -> Bool should also be applied on the result of the function, so:
import Control.Applicative(liftA2)
isAsciiAlpha :: Char -> Bool
isAsciiAlpha = liftA2 (||) C.isAsciiLower C.isAsciiUpper
isValid :: String -> Bool
isValid n
| any (not . liftA2 (||) isAsciiAlpha C.isSpace) n = False
| otherwise = ys > 1 && sum xxs `mod` 10 == 0
where -- …
You can also make use of (<||>) :: Applicative a => a Bool -> a Bool -> a Bool or its shortcircuitng version (||^) :: Monad m => m Bool -> m Bool -> m Bool of the protolude package.

How to pass not a function that returns a boolean in another function?

I want to negate a function in the if clause of another function like bellow:
isBig :: Integer -> Bool
isBig n = n > 9999
function :: Integer -> Integer
function n =
if not isBig n then ... else ...
It complies when it's just 'if isBig n then else' but I'm not sure why it doesn't work for 'not isBig' as I get this error:
*Couldn't match expected type Bool' with actual type Integer -> Bool'
Many thanks in advance.
You want not (isBig n). not isBig n tries to pass two arguments to not, both isBig and n. isBig is an Integer -> Bool but a Bool is expected, hence the error.
In general, function application in Haskell is left-associative, meaning that an expression like this:
f 2 3 5
Is parsed like this:
(((f 2) 3) 5)
Likewise, the arrows in function types are right-associative, so for example if we had this definition for f:
f :: Int -> Int -> Int -> Int
f x y z = x * y + z
That type signature is the same as:
f :: Int -> (Int -> (Int -> Int))
So it looks like this as you apply more arguments:
f :: Int -> (Int -> (Int -> Int))
(f 2) :: (Int -> (Int -> Int))
((f 2) 3) :: (Int -> Int)
(((f 2) 3) 5 :: Int
==
f :: Int -> Int -> Int -> Int
f 2 :: Int -> Int -> Int
f 2 3 :: Int -> Int
f 2 3 5 :: Int
When you’re applying a chain of functions to an argument, you end up with parentheses associating to the right:
f (g (h x))
In this case it’s common to use the $ operator, which is right-associative and has low precedence, just to reduce the nesting of brackets:
f $ g $ h x
And you can do so in your case: not $ isBig n
You can also use composition to factor out the chain of functions and apply it to different arguments elsewhere:
fgh = f . g . h
fgh x
==
(f . g . h) x
==
f (g (h x))
isNotBig = not . isBig
isNotBig n
==
(not . isBig) n
==
not (isBig n)

Occurs check: cannot construct the infinte type

I'm trying to construct a list of all prime numbers using the sieve method:
primes remNum =
let i = head remNum
in i : primes (filter (\(x) -> x mod i /= 0) (tail remNum))
The error that I'm getting is:
* Occurs check: cannot construct the infinite type:
t ~ (a -> a -> a) -> t -> a1
Expected type: [t]
Actual type: [(a -> a -> a) -> t -> a1]
* In the first argument of `head', namely `remNum'
In the expression: head remNum
In an equation for `i': i = head remNum
* Relevant bindings include
i :: t (bound at lib.hs:30:7)
remNum :: [(a -> a -> a) -> t -> a1] (bound at lib.hs:29:8)
primes :: [(a -> a -> a) -> t -> a1] -> [t] (bound at lib.hs:29:1)
I don't understand why remNum is bound to [(a-> a -> a) -> t -> a1] while i is bound to t, since surely head :: [a] -> a would imply remNum::[t]?
So the idea with this is that it is supplied a lazy list of all numbers and then essentially maintains a list of removed values.
It would be called:
numsFrom n = n : numsFrom (n + 1)
primes numsFrom 2
x mod i
is not what you intended. You want to use
x `mod` i
The problem with the first is that since both i and x are from the list, they must have the same type. Let's call that type X. What is X? Well, since we use x mod, it should start with mod's type:
type X = (Integer -> Integer -> Integer) -> …
Since the other "parameter" is i, which has the same type as x, we end up with:
type X = (Integer -> Integer -> Integer) -> X -> …
which is an infinite type.
So the proper solution would be
primes remNum =
let i = head remNum
in i : primes (filter (\(x) -> x `mod` i /= 0) (tail remNum))
or
primes remNum =
let i = head remNum
in i : primes (filter (\(x) -> mod x i /= 0) (tail remNum))
or (with pattern matching)
primes (i:remNums) = x : primes (filter (\x -> mod x i /= 0) remNums)

Understanding Haskell Pattern Matching

Using pattern matching, define a function:
ifThenElse :: Bool -> Int -> Int -> Int
which gives its second argument if the condition (the first argument) is True, and the
third argument if the condition is False (for example, ifThenElse (3 > 5) 7 12 gives
12).
How would I go about writing this?
Here is what I have so far:
ifThenElse :: Bool -> Int -> Int -> Int
ifThenElse True x1 y1 = x1
ifThenElse False x1 y1 = y1
Here is a hint.
You can solve your problem using if-else statement:
ifThenElse :: Bool -> Int -> Int -> Int
ifThenElse p x y = if p then x else y
But, Bool is enumerated type with only two values. You can match ifThenElse's arguments with Bool values and define what to do if function gets False or True. It's called pattern-matching:
ifThenElse :: Bool -> Int -> Int -> Int
ifThenElse False = ...
ifThenElse True = ...
And at last, if you use pattern-matching and in some case resulting value doesn't depend from particular argument, you can hide that argument using placeholder:
f :: Int -> Int -> Int -> Int
f 0 x y = x + y
f 1 _ y = y -- in case of getting `1` function returns just `y`

Get primes below x

I'm trying to write a procedure that returns a list of all primes below a given number.
For example:
Prelude>primes 8
[2,3,5,7]
When I try to load the file I get Parse error in pattern Failed, modules loaded: none. If someone could point me in the right direction I would be grateful.
primes :: Int -> [Int]
primes x < 2 = []
primes x | isPrime x == True = primes (x - 1) ++ x
| otherwise = primes (x - 1)
isPrime :: Int -> Bool
isPrime x | x < 2 = False
| x == 2 || x == 3 = True
| divEven x == True = False
| divOdd x 3 == True = False
| otherwise = True
divEven :: Int -> Bool
divEven x | mod x 2 == 0 = True
| otherwise = False
divOdd :: Int Int -> Bool
divOdd x num | mod x num == 0 == True
| num <= x/2 = divOdd x (num + 2)
| otherwise = False
A collection of small mistakes.
Your syntax is incorrect.
primes x < 2 = []
Probably you meant
primes x | x < 2 = []
Similarly, where you write
divOdd x num | mod x num == 0 == True
you probably meant
divOdd x num | mod x num == 0 = True
The type signature
divOdd :: Int Int -> Bool
is not valid. You probably meant
divOdd :: Int -> Int -> Bool
x is of type Int, and (/) :: Fractional a => a -> a -> a cannot be applied to it. You probably mean num <= x `div` 2 or 2 * num <= x.
divOdd :: Int Int -> Bool
divOdd x num | mod x num == 0 == True
| num <= x/2 = divOdd x (num + 2)
| otherwise = False
x is of type Int, not [Int]. (++) :: [a] -> [a] -> [a] will not apply to it.
primes x | isPrime x == True = primes (x - 1) ++ x
Perhaps you meant
primes x | isPrime x == True = primes (x - 1) ++ [x]
Finally, this is a fairly inefficient way of generating primes. Have you considered a sieve? Prime numbers - HaskellWiki may be a bit difficult for you right now, but shows many different strategies.
Here's a re-write of your functions using list comprehensions (also in Wikipedia), perhaps this is more visually apparent:
primes :: Int -> [Int]
primes x | x<2 = []
| x<4 = [2..x]
| True = primes (x-1) ++ [x | isPrime x]
your isPrime is
isPrime x = x > 1 &&
( x < 4 ||
and [ rem x n /= 0 | n <- 2 : [3,5..(div x 2)+2] ] )
and is a function defined in standard Prelude. It will test entries in a list, left to right, to see if all are True. It will stop on the first False entry encountered, so the rest of them won't get explored.
Sometimes when the code is more visually apparent it is easier to see how to improve it.

Resources