2

Clojure 新手,想知道如何使用它来使我用其他语言更容易编程。

我想做的一件事是使用 Clojure 进行代码生成。

例如,给定来自数据文件(EDN 格式)的输入,我应该如何(1)遍历这个结构或(2)将数据推送到现有的模板机制中?

下面的数据将用于定义简单的 REST API,以便您可以从中生成客户端。使用不同的模板生成多种语言的客户端。

(:restcall "GetAccountBalance" 
  {:method "GET" :path "account/balance"}
  {:id int})

(:restcall "GetLastTransactions" 
  {:method "GET" :path "account/transactions"}
  {:page int})

结果代码将类似于

public void GetAccountBalance(int id) 
{
    var input = new { id = id };
    callIntoRestLibrary("GET", "account/balance", input);
}

public void GetLastTransactions(int page) 
{
    var input = new { page = page };
    callIntoRestLibrary("GET", "account/transactions", input);
}

注意:我的最终目标是通过 C# 将这些作为 System.Net.Http.HttpClient 调用,但也能够将它们转换为 JavaScript/Ajax 调用

4

1 回答 1

3

使用 Clojure 进行模板化有多种选择。Clojure Toolbox是一个值得一看的地方。

这是一个带有clostache的示例,它是mustache的一个小型库(358 loc)实现。

(ns so.core
  (:require [clostache.parser :refer (render)]))

(def template "
public void {{restcall}}({{id}} id) 
{
    var input = new { id = id };
    callIntoRestLibrary(\"{{method}}\", \"{{path}}\", input);
}")

(def data 
  {:restcall "GetAccountBalance" 
   :method "GET" :path "account/balance" :id "int"})


(print (render template data))

输出:

public void GetAccountBalance(int id)
{
    var input = new { id = id };
    callIntoRestLibrary("GET", "account/balance", input);
}

消除对阅读 EDN意味着什么的困惑。

(spit "foo.txt" (prn-str data))

现在该文件foo.txt包含 的文本表示data,大概是您的起点。

(def data2 (with-open [r (java.io.PushbackReader. (java.io.FileReader. "foo.txt"))] 
             (clojure.edn/read r)))

(= data data2) ;=> true

因此,read不仅拉入文本,还将其解析为数据表示形式。

于 2014-04-29T02:42:48.790 回答