こういうのもできるのか。
Prelude> [x| x <- [0..3], y <- [0..3]] [0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3] Prelude> [y| x <- [0..3], y <- [0..3]] [0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3]
takatoh's blog – Learning programming languages.
こういうのもできるのか。
Prelude> [x| x <- [0..3], y <- [0..3]] [0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3] Prelude> [y| x <- [0..3], y <- [0..3]] [0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3]
問題1。
matrix n = [[x+(n^2*y) | x <- [1..n^2]] | y <- [0..n^2-1]]
*Main> matrix 2 [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] *Main> matrix 3 [[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,5 3,54],[55,56,57,58,59,60,61,62,63],[64,65,66,67,68,69,70,71,72],[73,74,75,76,77, 78,79,80,81]]
問題2。Data.List
の transpose
そのままでは芸がないので。
transpose' m = [[m!!x!!y| x <- [0..l]] | y <- [0..l]] where l = length m - 1
*Main> transpose' $ matrix 2 [[1,5,9,13],[2,6,10,14],[3,7,11,15],[4,8,12,16]]
問題3はあとで。
追記:
問題2の別解。foldr
を使う。これなら正方行列でなくてもOK。
transpose'2 m = foldr (\a b -> zipWith (:) a b) (replicate (length m) []) m
*Main> transpose'2 $ matrix 2 [[1,5,9,13],[2,6,10,14],[3,7,11,15],[4,8,12,16]]