Wednesday, April 21, 2010

Blog changes and haskell exercise

Hey there ! Just as I've promised I've came up with some Haskell exercises (with answers). To do that I had to post some code, which is not really convenient on Blogger. Fortunately there is a solution ! What I've found on the web is easy syntax highlighting for blogger.
Enjoy !


So now with the exercises :

1. Pretty standard problem - find all prime numbers up to a number given in the argument.
2. Function that takes a function (two numbers as arguments) and a list of numbers and returns a list of those two argument functions but already applied to numbers in the list given. That way we gain a list of functions taking one number.
3. Find all automorphic numbers up to a given number.
4. Rewrite the following functions so they use (.) operator :
one = sum ( takeWhile (<10000) (filter isPrime  [1..]) )
two = map (\x -> cos (sqrt x))

Solutions:
1.
allPrime :: (Integral a) => a -> [a]
allPrime range = filter isPrime [2..range]

isPrime :: (Integral a) => a -> Bool
isPrime x = not (isNotPrime 1 x)

isNotPrime :: (Integral a) => a -> a -> Bool
isNotPrime dv nr
    | dv == nr = False
    | dv == 1 = False || isNotPrime 2  nr
    | otherwise = nr `mod` dv==0 || isNotPrime (dv+1) nr
2.
partialL ::( Num a ) => (a-> a -> b) -> [a] -> [ a->b ]
partialL _ [] = []
partialL f (x:xs) = f x : partialL f xs
Usage :
let bla = partialL (\x -> \y -> x+y) [1,2,3,4]
map ($ 2) bla
[3,4,5,6]

3.
automorphic :: Int -> [Int]
automorphic y = [ x | x <- (take y [1..]), show x == (splitter x) ]

splitter :: (Num a) =>  a -> [Char]
splitter x = snd (  splitAt ( length (show sq) - length (show x) ) (show sq)  )
 where sq = x^2

4.
one = sum . takeWhile (<10000) . filter isPrime  [1..]
two = map (cos . sqrt)

No comments:

Post a Comment