LoginSignup
6
2

More than 3 years have passed since last update.

Pythonで書かれたLisp方言HyでFlaskを動かす

Posted at

動機

Lispで実際にアプリケーション書いてみたいと思ったけどCommon LispやSchemeなどのLisp方言はライブラリの管理とかよくわかんないしどうしようかと思ったところでPythonで書かれたLisp方言のHyを知ったのでFlaskを動かしてみる。HyだとPythonのVM上で動くのでFlaskだろうがDjangoだろうがKerasだろうが書ける。神。

Hyのインストール

pipenvを使ってインストールします。

$ mkdir hy_flask
$ cd hy_flask
$ pipenv --python 3.6.5
$ pipenv install hy

Python -> Hy

変数代入

hello = 'Hello world!'
(setv hello "Hello world!")

hyではシングルクォーテーションで囲っても文字列にならないので注意

関数定義

def say(hello):
    print(hello)
(defn say [hello]
  (print hello))

四則演算

print(5 + 2)
print(5 - 2)
print(5 * 2)
print(5 / 2)
(print (+ 5 2))
(print (- 5 2))
(print (* 5 2))
(print (/ 5 2))

インポート

import random
from operator import add, sub
import numpy as np
(import random)
(import [operator [add sub]])
(import [numpy :as np])

デコレータ

def deco(func):
    def wrap():
        print('--start--')
        func()
        print('--end--')
    return wrapper

@deco
def hello():
    print('Hello Decorator')

hello()
(defn deco [func]
  (fn []
    (print "--start--")
    (func)
    (print "--end--")))

#@(deco
  (defn hello []
    (print "Hello Decorator")))

(hello)

これで一通りFlaskでHello Worldくらいの文法は十分だと思うのでFlask動かしてみる。

Hy + Flask

前述のHyをインストールしたディレクトリでFlaskをインストールしてプログラムを書いていく

$ pipenv install flask
$ touch app.hy
app.hy
(import [flask [Flask]])

(setv app (Flask __name__))

#@((app.route "/")
  (defn hello []
    (return "Hello World!")))

(app.run)

実行

$ pipenv shell
$ hy app.hy

もしくは

$ pipenv run hy app.hy

http://localhost:5000にアクセスしてHello World!が出力されていれば終わり。

6
2
0

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
6
2