
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Display Prime Numbers Between Intervals Using Function in Haskell
In Haskell, we can Display Prime Numbers Between Intervals using user-defined function along with filter function and recursion. In the first example we are going to use user-defined, (isPrime) function with (primeInRange a b = filter isPrime [a..b] ) function and in the second example, we are going to use recursion with base and recursive case.
Algorithm
Step 1 ? The Data.List library is imported.
Step 2 ? The user-defined isPrime function is defined as,
Step 3 ? Program execution will be started from main function. The main() function has whole control of the program. It is written as main = do.
Step 4 ? The variables named, "lower" and "upper" are being initialized. It will hold the range between which the prime numbers is to be printed.
Step 5 ? The resultant prime numbers under the defined range is printed to the console using ?print' function after the function is called.
Example 1
In this example, we are going to see that how we can display prime numbers between two interval by using user defined functions using filter function.
import Data.List (find) isPrime :: Integer -> Bool isPrime n | n <= 1 = False | n == 2 = True | even n = False | otherwise = all (\x -> n `mod` x /= 0) [3,5..(n-1)] primeInRange :: Integer -> Integer -> [Integer] primeInRange a b = filter isPrime [a..b] main :: IO () main = do let lower = 10 upper = 20 print (primeInRange lower upper)
Output
[11,13,17,19]
Example 2
In this example, we are going to see that how we can display prime numbers between two interval by using user defined functions using recursion.
import Data.List (find) isPrime :: Integer -> Bool isPrime n | n < 2 = False | n == 2 = True | n `mod` 2 == 0 = False | otherwise = all (\x -> n `mod` x /= 0) [3,5..(floor . sqrt . fromIntegral $ n)] primeInRange :: Integer -> Integer -> [Integer] primeInRange a b | a > b = [] | isPrime a = a : primeInRange (a+1) b | otherwise = primeInRange (a+1) b main :: IO () main = do let lower = 2 upper = 30 print (primeInRange lower upper)
Output
[2,3,5,7,11,13,17,19,23,29]
Conclusion
A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. In Haskell, to display the prime numbers between intervals we can use user-defined functions using filter function and recursion.