kotapiku
9/13/2017 - 2:15 PM

kokuyouwind/haskell-exercises chapter1,3の解答

kokuyouwind/haskell-exercises chapter1,3の解答

-- マンハッタン距離(chapter1)
manlen :: (Int, Int) -> (Int, Int) -> Int
manlen p1 p2 = abs ((fst p1)-(fst p2)) + abs ((snd p1)-(snd p2))

points :: Int -> [(Int, Int)]
points x = [(x1,x2) | x1 <- [-1*x..x], x2 <- [-1*x..x]]

mancircle :: Int -> [(Int, Int)]
mancircle x = [p | p <- points x, manlen p (0,0) == x]

-- トリボナッチ数列(chapter3)
tri_pattern :: Int -> Int
tri_pattern 0 = 0
tri_pattern 1 = 0
tri_pattern x = tri_guard (x-1) + tri_guard (x-2) + tri_guard(x-3)

tri_guard :: Int -> Int
tri_guard x
    | x == 0 = 0
    | x == 1 = 0
    | x == 2 = 1
    | otherwise = tri_guard (x-1) + tri_guard (x-2) + tri_guard(x-3) 

tri_case :: Int -> Int
tri_case x = case x of  0 -> 0
                        1 -> 0
                        2 -> 1
                        x -> tri_guard (x-1) + tri_guard (x-2) + tri_guard(x-3)

-- タプル数
qadd :: (Int, Int) -> (Int, Int) -> (Int, Int)
qadd a b
    | (snd a) == 0 = error "second of tuple number is 0"
    | (snd b) == 0 = error "second of tuple number is 0"
    | otherwise = ((fst a) * (snd b) `div` g + (fst b) * (snd a) `div` g, (snd a) * (snd b) `div` g)
    where g = fromIntegral $ gcd (snd a) (snd b) 

qequal :: (Int, Int) -> (Int, Int) -> Bool
qequal a b
    | (snd a) == 0 = error "second of tuple number is 0"
    | (snd b) == 0 = error "second of tuple number is 0"
    | otherwise = (fromIntegral (fst a)) / (fromIntegral (snd a)) == (fromIntegral (fst b)) / (fromIntegral (snd b))

qlist :: (Int, Int) -> [(Int, Int)]
qlist a
    | (snd a) == 0 = error "second of tuple number is 0"
    | otherwise = foldr (\n xs -> (x*n,y*n):(-1*x*n,-1*y*n):xs) [] [1..]
    where 
        x = div (fst a) $ gcd (fst a) (snd a) 
        y = div (snd a) $ gcd (fst a) (snd a)