Skip to content

Instantly share code, notes, and snippets.

@tuttlem
Last active December 10, 2015 08:48
Show Gist options
  • Select an option

  • Save tuttlem/4410052 to your computer and use it in GitHub Desktop.

Select an option

Save tuttlem/4410052 to your computer and use it in GitHub Desktop.
haskell - primes
{- LANGUAGE ForeignFunctionInterface #-}
module Prime where
import Foreign.C.Types
-- | Take a boolean and convert it to an integer
bool_to_int :: Bool -> Int
bool_to_int False = 0
bool_to_int True = 1
-- | Brute force division style prime number testing
is_prime :: Int -> Int
is_prime x = bool_to_int ptest
where divisible = [n | n <- [3,5..(x-1)], x `mod` n == 0]
ptest = length (divisible) == 0
-- | Interface exposed into C land
is_prime_hs :: CInt -> CInt
is_prime_hs = fromIntegral . is_prime . fromIntegral
-- | Export symbols into C land
foreign export ccall is_prime_hs :: CInt -> CInt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment