Learn Nim with Python (from the beginning of the year).

Today, I'm going to expose my notes about learning Python with Nim to my older brothers who are using C ++ / objective-c in practice or who are Pythonistas. ... From the beginning of the year, you'll be working with big data in Python + C. I felt like it wouldn't work even if I used nim, and I'm grateful.

One of the features of the compilation language Nim (formerly Nimrod)

Formerly Nimrod, Nim, which has been under development since around 2008. To get Python users to understand its features, I think it's a good idea to take a look at the following code in the Japanese version of wikipedia, nim.

wikipedia.nim


proc reverse(s: string): string =
  result = "" #Implicit result variable
  for i in countdown(high(s), 0):
    result.add s[i]

var str1 = "Reverse This!"
echo "Reversed: ", reverse(str1)

A little bit of wikipedia commentary:

--Focus on the implicit result variable. In Nim, procedures whose return type is not void have an implicit result variable. The result variable holds the return value of the procedure. --countdown in a for loop is an iterator. Here, an iterator that counts down from the character string length obtained by high (s) to 0 is described.

Although Nim is a typed compilation language, it can be written like a scripting language.

It seems that Nim began to be known in Japan around the blog about five years ago by Takano32, "Let's write FizzBuzz with Nimrod!".

Takano32, a Ruby committer, then immediately posted an entry, "How can I use Python with Nimrod !?"

Yes, there are quite a few people trying to use python and nim together (what about the relationship between ruby and nim?).

So, this time, I'd like to call nim from python and think about how to use it.

* So, if you are a python user who is interested in nim, which has the same execution speed as C language, not horse-like, please read the source code of nim and the original document and post it on your blog. .. I will be saved ^ _ ^ *

Call nim from python.

Basically, if you follow Connecting Nim to Python, it's quick. What we are doing is creating a so-called shared library in C language from the source code of nim. Binaries are execution environment dependent. Below is an example on a Mac. If you have xcode and the latest brew, you only need to install nim as follows.

brew install nim

First, prepare nim code with only one procedure (function),

fn1.nim


proc summer*(x, y: float): float {. exportc, dynlib .} =
  result = x + y

Below, it will be made into a shared library.

nim c --app:lib fn1.nim

The python code that calls the generated libfn1.dylib is below (using the python 2.7 that comes with the Mac from the beginning): Since it is a C language shared library call, use ctypes.

py2nim1.py


from ctypes import *

def main():
    test_lib = CDLL('./libfn1.dylib')

    # Function parameter types
    test_lib.summer.argtypes = [c_double, c_double]

    # Function return types
    test_lib.summer.restype = c_double

    sum_res = test_lib.summer(1.0, 3.0)
    print('The sum of 1.0 and 3.0 is: %f'%sum_res)

if __name__ == '__main__':
    main()

If you pay attention to the double type in the 64-bit environment, you can get the answer "4.0" from nim.

Is it used, for example, in-house batch processing system?

In an environment where numpy, pypy, micropython, R18python ... etc. are not obscene and specialized py terms are used in pursuit of execution speed, nim may be able to blend in smoothly. Even if it doesn't, "Hey, look at this, you. What do you think of this guy? ”-If you have an environment like“ It's really big ... (in terms of computational power) ”, it's possible to challenge the process with python + C language + nim. It seems to be.

Since about 20 years when it was a minor language, innumerable code has been written by fierce men, and there are various "arts" in python. For example, the Mac environment contains an Objective-c (++) calling library called PyObjC, and you can immediately call nim while calling a GUI written in Objective-c with python. Since the GUI call description on the python side is long, put the code in gist.

Execution example: スクリーンショット 2016-12-15 05.12.54.png

Creating a GUI for users to call a calculation library written in nim is much easier with python. Nim, the compilation language, can concentrate on data processing descriptions that call C / C ++, which has a high affinity, as appropriate.

Continue

... and I wrote about the ratio and common sense about nim, which is now limited to the material language. But, big brother, don't worry. With this as a starting point, I will write a story post on the subject of IoT in the near future.

Recommended Posts

Learn Nim with Python (from the beginning of the year).
Learning notes from the beginning of Python 1
Learning notes from the beginning of Python 2
Study from the beginning of Python Hour1: Hello World
Study from the beginning of Python Hour8: Using packages
First Python 3 ~ The beginning of repetition ~
Existence from the viewpoint of Python
Call python from nim with Nimpy
Learn the basics of Python ① Beginners
[Python] Understand the self of the class. Learn the role of self from the execution result with or without self.
Check the existence of the file with python
Omit BOM from the beginning of the string
I want to output the beginning of the next month with Python
From the introduction of JUMAN ++ to morphological analysis of Japanese with Python
Learn the design pattern "Singleton" with Python
Intuitively learn the reshape of Python np
Learn the design pattern "Facade" with Python
Get the contents of git diff from python
Prepare the execution environment of Python3 with Docker
2016 The University of Tokyo Mathematics Solved with Python
[Note] Export the html of the site with python.
Calculate the total number of combinations with python
Check the date of the flag duty with Python
Finding the beginning of Abenomics from NT magnification 2
Convert the character code of the file with Python3
Finding the beginning of Abenomics from NT magnification 1
[Python] Determine the type of iris with SVM
The beginning of cif2cell
Learn Python with ChemTHEATER
the zen of Python
Deep Learning from scratch The theory and implementation of deep learning learned with Python Chapter 3
The wall of changing the Django service from Python 2.7 to Python 3
[Python] Get the text of the law from the e-GOV Law API
The first algorithm to learn with Python: FizzBuzz problem
Destroy the intermediate expression of the sweep method with Python
Visualize the range of interpolation and extrapolation with python
Mathematical understanding of principal component analysis from the beginning
Get the return code of the Python script from bat
Python points from the perspective of a C programmer
Calculate the regression coefficient of simple regression analysis with python
Learn the design pattern "Chain of Responsibility" in Python
Summary of the basic flow of machine learning with Python
Principal component analysis using python from nim with nimpy
Get the operation status of JR West with Python
Install the latest Python from pyenv installed with homebrew
[Basics of data science] Collecting data from RSS with python
Extract the band information of raster data with python
From the initial state of CentOS8 to running php python perl ruby with nginx
Get the value of a specific key in a list from the dictionary type in the list with Python
Extract images and tables from pdf with python to reduce the burden of reporting
About the ease of Python
Call the API with python3.
Beginning with Python machine learning
About the features of Python
With skype, notify with skype from python!
The Power of Pandas: Python
I tried to find the entropy of the image with python
Try scraping the data of COVID-19 in Tokyo with Python
DJango Note: From the beginning (simplification and splitting of URLConf)
Extract template of EML file saved from Thunderbird with python3.7
I tried using the Python library from Ruby with PyCall