I am a beginner in haskell and I tried to define a simple function for Sieve of Eratosthenes but it says error:
• Couldn't match expected type ‘Bool -> Bool’
with actual type ‘Bool’
• The function ‘or’ is applied to two value arguments,
but its type ‘t Bool -> Bool’ has only one
In the expression: or (mod n x) (divl l x)
In an equation for ‘divl’: divl (n : l) x = or (mod n x) (divl l x)
|
13 | divl (n:l) x = or (mod n x) (divl l x)
erat l [] = l
erat l (x:t) = if divl l x then erat l t else erat (x:t) l
divl (n:l) x = or (mod n x) (divl l x)
divl [] x = True
I tried to write that as an operator with "`" but nothing worked
CodePudding user response:
or
is not the boolean OR operator; that's (||)
. or
takes a list (well, Foldable
) of Boolean values and returns True
if at least one value is True
.
> or []
False
> or [True, False]
True
(Note that or []
is defined to be False
to preserve the identity or xs || or ys == or (xs ys)
. As a concrete example, or [] || or [False] == or [False]
.)
CodePudding user response:
Try to use (||) :: Bool -> Bool -> Bool
instead of or :: Foldable t => t Bool -> Bool
https://hackage.haskell.org/package/base-4.17.0.0/docs/Prelude.html#v:-124--124-
https://hackage.haskell.org/package/base-4.17.0.0/docs/Prelude.html#v:or
i.e. mod n x || divl l x
or or [mod n x, divl l x]
.
CodePudding user response:
You need to check if the modulo is zero, or one of the remaining, you use (||) :: Bool -> Bool -> Bool
:
divl (n:l) x = mod n x == 0 || divl l x
divl [] x = False
The basecase should be False
, otherwise it will always return True
. It is probably better to work with any
however:
divl ls x = any ((0 ==) . (`mod` x)) ls