-
-
Save heitor-lassarote/dc862c40c9a7fb9b7693fa1467d61605 to your computer and use it in GitHub Desktop.
Typed Template Haskell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE TemplateHaskell #-} | |
import TH | |
main :: IO () | |
main = do | |
let numbers = $$(primesUpTo' 10000) | |
putStrLn "Which prime number do you want to know?" | |
input <- readLn | |
if input < length numbers | |
then print (numbers !! (input - 1)) | |
else putStrLn "Number too big!" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Primes where | |
isPrime :: Integer -> Bool | |
isPrime n | |
| n <= 1 = False | |
| n == 2 = True | |
| even n = False | |
| otherwise = go 3 | |
where | |
go i | |
| i >= n = True | |
| n `mod` i == 0 = False | |
| otherwise = go (i + 2) | |
primesUpTo :: Integer -> [Integer] | |
primesUpTo n = go 2 | |
where | |
go i | |
| i > n = [] | |
| isPrime i = i : go (i + 1) | |
| otherwise = go (i + 1) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE TemplateHaskell #-} | |
module TH where | |
import Language.Haskell.TH | |
import Primes (isPrime) | |
primesUpTo' :: Integer -> Q (TExp [Integer]) | |
primesUpTo' n = go 2 | |
where | |
go i | |
| i > n = [||[]||] | |
| isPrime i = [||i : $$(go (i + 1))||] | |
| otherwise = go (i + 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment