LoginSignup
2
0

More than 5 years have passed since last update.

Nim by Example で行列の和の例があったので

Last updated at Posted at 2017-09-27

少し謎

Nim by Example - Array
を眺めてて 2x2の行列を定義していたので動かしていましたが,そのまま動かすと駄目でした.

type
  Matrix[W,H:static[int]] = array[1..W,array[1..H,int]]

let 
  mat1 : Matrix[2,2] = [[1,0],
                        [0,1]]
  mat2 : Matrix[2,2] = [[0,1],
                        [1,0]]

proc `+` [W,H](a,b: Matrix[W,H]):Matrix[W,H]=
  for i in 1..high(a):
    for j in 1..high(a[0]):
      result[i][j] = a[i][j] + b[i][j]


echo repr(mat1+mat2)

こんな感じで echo で reprをしないとコンパイル通りませんでした. うーん...

追記(2017/10/23)

コメントのヒントを頼りに $ を実装してみました。

type
  Matrix[W,H:static[int]] = array[1..W,array[1..H,int]]

let 
  mat1 : Matrix[2,2] = [[1,2],
                        [0,1]]
  mat2 : Matrix[2,2] = [[0,0],
                        [3,3]]

proc `+` [W,H](a,b: Matrix[W,H]):Matrix[W,H]=
  for i in 1..high(a):
    for j in 1..high(a[0]):
      result[i][j] = a[i][j] + b[i][j]

proc `$` [W,H](a: Matrix[W,H]):string = 
  var str=""
  for i in 1..high(a):
    for j in 1..high(a[0]):
      str &= $a[i][j] & " "
    str &= "\n"
  return str

echo mat1 + mat2
2
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0