2014-02-22 47 views
0

我正在製作一個簡單的Web應用程序來幫助我的老師朋友計算他們的成績。我有我下面的工作當前代碼位:解析打嗝文本字段的字符串數據以用於Clojure函數

(defn home [& [weights grades error]] 
     (layout/common 
     [:h1 "Welcome to Clojure-grade"] 

     [:hr] 

     (form-to [:post "/"] 

       [:p "Enter the weights for your various grades below. 
        Of course, all of the numbers should add up to 100%, as in the example, below." 
        (text-field {:placeholder "40 10 50"} "weights" weights)] 

       [:p "Enter all of the grades for each student. 
        Make sure that each of the grades is ordered to correspond 
        to its matching weight above. use brackets to separate students from each other. 
        The following example shows grades for 4 students. Format your grades according to   
        the number of students in your class:" 
        (text-area {:rows 40 :cols 40 :placeholder 
           "[89 78 63] 
           [78 91 79] 
           [54 85 91] 
           ..." } "grades" grades)] 
       (submit-button "process")))) 

(defn process-grades [weights grades] 
    (->> (float grades) 
     (map (partial percentify-vector (float weights))) 
     (mapv #(apply + %)))) 

(defroutes app 
    (GET "/" [] 
     {:status 200 
     :headers {"Content-Type" "text/html"} 
     :body home}) 
    (POST "/" [weights grades] (process-grades weights grades)) 
    (ANY "*" [] 
     (route/not-found (slurp (io/resource "404.html"))))) 

(defn wrap-error-page [handler] 
    (fn [req] 
    (try (handler req) 
     (catch Exception e 
      {:status 500 
      :headers {"Content-Type" "text/html"} 
      :body (slurp (io/resource "500.html"))})))) 

我猜測該數據將被綁定到相應的weightsgrades符號的字符串。但是,我需要彈出這些引號以在我的計算函數中使用浮點數和向量。我怎樣才能做到這一點?我也是這樣的初學者,所以如果我的代碼中有任何錯誤,或者我正在以錯誤的方式處理事情,請告訴我。另外,如果您需要更多名稱空間或project.clj信息,請問我將展開。

回答

0

您可以使用Java的互操作來將字符串轉換爲浮動或整數,但慣用的方法是使用讀字符串

(process-grades 
    (read-string weights) 
    (read-string grades)) 
+0

在這裏找到一個更好的解釋http://stackoverflow.com/a/2640320/1552130 – KobbyPemson

+0

我感謝你對此的幫助。我已經添加了你給我的建議,但它仍然不會呈現。我現在有一個不同的問題。它略有不同,所以我在這裏問了一個新問題:[link](https://stackoverflow.com/questions/21969402/clojure-heroku-web-app-page-wont-render-in-browser)。請看一看。 – kurofune