Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension and type problems (Haskell)

I have annoying syntax error in following construction:

isPrime n = if numOfDivisors n == 0 then True else False            
    where numOfDivisors n = length $ [x | x <- [2..ceiling (sqrt n)], n `mod` x == 0]

How I can fix it? I'm new to Haskell, so I don't know what's wrong in [2..ceiling (sqrt n)].

Thanks (sorry for my poor brain).

like image 623
vortexxx192 Avatar asked Apr 26 '26 12:04

vortexxx192


1 Answers

You're using both sqrt and mod with n--the first requires a floating point type, the latter requires an integral type. You probably want the latter, and to use sqrt (fromIntegral n) instead.

Some other unsolicited advice:

  • There is no possible reason to do if foo then True else False. Just use the boolean expression alone.

  • Function arguments are in scope in the where clause, so numOfDivisors doesdn't need n as an argument.

  • Don't use length to check if a list is empty. Use null on the list of divisors instead.

like image 199
C. A. McCann Avatar answered Apr 28 '26 21:04

C. A. McCann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!