Clojure读取线将其转换为有用的矢量

时间:2014-09-08 02:52:25

标签: clojure

问题:如何将Read-Line转换为可用的向量以传入另一个函数以便工作。

(defn iAcceptUserInputAsAVector [a b c] ( )) ; I do work with the userInput as a vector

(defn input []
   (let [userKeyboardInput ( read-line)]
     (
       [userKeyboardInput]; doesnt work I tried (vector userKeyboardInput)
     )
   )
 )

更新1:我的进展到目前为止归功于noisesmith

(defn input []( let [userKeyBoardInput [(read-line)]]
                (println userKeyBoardInput)
                ))

更新2我当前的解决方案和工作......我想它可以做得更好

(defn split-by-whitespace [s]
    (clojure.string/split s #"\s+"))

(defn input []
  ( let [userKeyBoardInput [(split-by-whitespace(read-line))]]
    ;Then insanity below is because I have to convert to integers, list then a vector. Why? map returns list 
    ;which I dont need instead I need a vector []
    ;Also the initial entry is returned as [[]] which I need to convert to [] for map to be able to take
    ;it as parameter. There probably a better way. Show me... 

    (def x (into[](map #(Integer/parseInt %) (into [](flatten [userKeyBoardInput])))))
     (println x)
     (myLoopFunc x); basically it takes my vector and does something .. not important

 ))

2 个答案:

答案 0 :(得分:1)

括号不是Clojure中的分组构造。

您的代码中存在两个主要错误:

((read-line))这会通过read-line获取一个字符串,然后尝试执行它。这将失败,字符串不会实现IFn

([userKeyboardInput])如果代码到目前为止,这也会失败,因为你不能在不提供任何参数的情况下将向量作为函数调用。

在clojure中,用parens包装东西通常意味着你想把它作为一个函数来执行。添加外来的parens很容易破坏。

答案 1 :(得分:1)

我将评论如何改进您当前的解决方案(删除源代码注释,添加亚麻布):

01: (defn split-by-whitespace [s]
02:     (clojure.string/split s #"\s+"))
03:
04: (defn input []
05:   ( let [userKeyBoardInput [(split-by-whitespace(read-line))]]
06:     (def x (into[](map #(Integer/parseInt %) (into [](flatten [userKeyBoardInput])))))
07:      (println x)
08:      (myLoopFunc x)
09:
10:  ))

函数split-by-whitespace看起来不错。请注意,它已经返回了一个向量。 (假设read-line返回"6 34 12"。然后split-by-whitespace会给您["6" "34" "12"])。因此,当您在第5行中调用它时,您的呼叫周围不需要[],因为您不希望向量中有向量。因此,您不再需要flatten。您可以只映射已有的矢量。然后,为您执行所需转换的函数将如下所示:

(defn string->number-vector   ; name is verbose but meaning is clear :)
  [s]
  (into []
    (map #(Integer/parseInt %)
         (split-by-whitespace s))))

您可以使用(myLoopFunc (string->number-vector (read-line)))调用它。