Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printing an array in Nim using echo

Tags:

nim-lang

Following the example here: https://nim-by-example.github.io/arrays/ and I am printing out an array. In the example they print the matrix, but the echo does not work and I get the following error:

matrix.nim(20, 7) Error: type mismatch: got (Matrix[2, 2])
but expected one of: 
system.$(x: T)
system.$(x: Enum)
system.$(x: int64)
system.$(x: bool)
system.$(x: char)
system.$(x: float)
system.$(x: string)
system.$(x: seq[T])
system.$(x: int)
system.$(x: uint64)
system.$(x: set[T])

I'm assuming this is versioning issue (I have im Compiler Version 0.12.0 installed on Ubuntu - probably not the latest).

However is there a smart way to print entities of any type. Is there a pprint as there is in Python?

like image 292
disruptive Avatar asked Feb 06 '23 07:02

disruptive


1 Answers

The $ operator referenced in the error message is Nim's "to string" operator. echo expects that such an operator is defined for the passed in type. It just happens that the latest version of the Nim's system module doesn't include a definition of $ for the array type.

You can easily fix the code by adding the following definition in your own module:

proc `$`[T,R](m: Matrix[T,R]): string =
  result = ""
  for r in countup(1, m.H):
    for c in countup(1, m.W):
      if c != 1: result.add " "
      result.add $m[r][c]

    result.add "\n"

This results in the expected output:

1 1
1 1

The closest thing to an universal printing operator is the Nim's repr proc, which tries to return the standard Nim's syntax representation of the values or the marshal module, which can encode an arbitrary type in json:

var sum = mat1 + mat2

echo sum.repr

import marshal
echo $$sum

In this particular example, both options yield the same result:

[[1, 1], [1, 1]]

[[1, 1], [1, 1]]
like image 174
zah Avatar answered Feb 21 '23 00:02

zah