summaryrefslogtreecommitdiff
path: root/fractran.hs
blob: 0d78ef9a312ee31e9244011186b26d824757337c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57



isInt :: (RealFrac a) => a -> Bool
isInt x =
    x == fromInteger (round x)



modulo :: Int -> Int -> Int
modulo x y =
    x - (x `div` y) * y



primeFactors :: Int -> [Int]
primeFactors x =
    let p = (\x e c -> if (x == 1)
                       then (reverse c)
                       else if (x `modulo` (head e) == 0)
                            then p (x `div` (head e)) e ((head e) : c)
                            else p x (tail e) c)
    in p x euler []



euler :: [Int]
euler =
    let f = (\list -> (head list) : (f (filter (\x -> x `modulo` (head list) /= 0) list)))
    in f [2..]



isPowerOf :: Int -> Int -> Bool
isPowerOf x y =
    case (compare x y) of
        LT -> False
        EQ -> True
        GT -> if (x `modulo` y == 0) then isPowerOf (x `div` y) y else False



fractran :: [(Int,Int)] -> Int -> [Int]
fractran program value =
    let prog = map (\(x,y) -> (fromIntegral x, fromIntegral y)) program
        f = (\p v -> if (p == [])
                     then []
                     else let (curX, curY) = head p
                              newV = v * curX / curY
                          in if (isInt newV)
                             then newV : (f prog newV)
                             else f (tail p) v)
        result = map round (f prog (fromIntegral value))
    in value : result