totem3
2/9/2012 - 3:07 PM

プログラミングHaskell第5章練習問題

プログラミングHaskell第5章練習問題

-- 1
-- square = sum [x^2 | x <- [1 .. 100]

--2
replicate :: Int -> a -> [a]
replicate n x = [x | _ <- [1 .. n]]

--3
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]

--4 
perfect :: Int -> [Int]
perfect n = [x | x <- [1..n], sum (factors x) == x * 2]

factors :: Int -> [Int]
factors n = [x | x <- [1 .. n], n `mod` x == 0]

--5
--わからない・・・

--6
find :: Eq a => a -> [(a,b)] -> [b]
find k t = [v| (k', v) <-t, k==k']

positions :: Eq a => a -> [a] -> [Int]
positions x xs = find x [(x',i)|(x',i) <- zip xs [0..n], x==x']
                 where n = length xs - 1

--7
scalarproduct :: [Int] -> [Int] -> Int
scalarproduct xs ys = sum [x*y|(x,y) <- zip xs ys]