遅々として進まない プログラミング Haskell ですが、5 章を読んで練習問題解いた。
square_sum :: Int -> Int square_sum n = sum [ x^2 | x <- [1 .. n]] replicate :: Int -> a -> [a] replicate n a = [ a | x <- [1 .. n]] pyths :: Int -> [(Int, Int, Int)] pyths n = [ (x, y, z) | x <- [1 .. n], y <- [1 .. n], z <- [1 .. n], x^2 + y^2 == z^2 ] perfects :: Int -> [Int] perfects n = [ x | x <- [ 1 .. n ], sum [ y | y <- factors x, y /= x ] == x ] where factors n = [ x | x <- [1 .. n], n `mod` x == 0 ] concat [[ (x,y) | y <- [4..6] ] | x <- [1..3]] positions :: Eq a => a -> [a] -> [Int] positions x xs = [ i | i <- find x (zip xs [ 1 .. n ]) ] where find k ts = [ b | (a, b) <- ts, a == k ] n = length xs scalarproduct :: [Int] -> [Int] -> Int scalarproduct xs ys = sum [ a * b | (a, b) <- zip xs ys ]
perfects は指定した値までの完全数をリストとして返す関数なんだけど、まさかこれだけシンプルに書けるとは正直思いませんでした。リスト内包表記の強力さが良くわかります。
perfects :: Int -> [Int] perfects n = [ x | x <- [ 1 .. n ], sum [ y | y <- factors x, y /= x ] == x ] where factors n = [ x | x <- [1 .. n], n `mod` x == 0 ] *Main> perfects 500 [6,28,496]