Last active
December 18, 2015 14:38
-
-
Save chomado/5798186 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 5-1 | |
sum [x^2 | x<-[1..100]] | |
-- 5-2 | |
replicate' :: Int -> a -> [a] | |
replicate' n a = [a | _ <- [1..n]] | |
-- 5-3 | |
-- 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] | |
-- 5-4 | |
-- 与えられた上限までに含まれる完全数全てを算出する関数perfects | |
factors :: Int -> [Int] | |
factors n = [x | x <- [ 1 .. n], n `mod` x == 0] | |
perfects :: Int -> [Int] | |
perfects n = [ x | x <- [1..n], x == sum(init (factors x))] | |
-- 5-6 | |
find :: Eq a => a -> [(a, b)] -> [b] | |
find k t = [ v | (k', v) <- t, k == k'] | |
-- > find 'b' [('a', 1), ('b', 2), ('c', 3), ('d', 4)] | |
-- [2, 4] | |
-- > zip ['a', 'b', 'c'] [1, 2, 3, 4] | |
-- [('a',1),('b',2),('c',3)] | |
positions :: Eq a => a -> [a] -> [Int] | |
--positions x xs = [i | (x', i) <- zip xs [0..], x == x'] | |
positions x xs = find x (zip xs [0..]) | |
-- ghci > positions False [True, False, True, False] | |
-- [1, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment