You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Clojure技术问题:如何将用户输入的两整数与Double存入列表?

Clojure处理用户输入:整数与Double存入列表的问题修复

问题背景

需要将控制台输入的12 1 5.30中的两个整数和一个Double存入列表,并逐行输出这三个值。现有代码执行时抛出ClassCastException,提示clojure.lang.LazySeq cannot be cast to class clojure.lang.IFn。

原代码

(ns clojure.partial.map
  (:gen-class))

(defn string-to-list [s]
  (re-seq #"\d+\d+(\d+)?\.(\d+)?" s))

(defn convert-seq-of-int-to-strings [ss]
  (let [new_partition (partition-all 2 ss)
        map-one (map #(Integer/parseInt %) (take 1 new_partition))
        map-two (map #(Double/parseDouble %) (take 1 (drop 1 new_partition)))
        map-concat (concat (map-one map-two))]
    (doseq [item map-concat]
      (println item))))

(def user-input (read-line))

(def new-sequence (string-to-list new-line))

(def converting-seq-to-list (convert-seq-of-int-to-strings new-seq))

; Expected Output: 
; 12
; 1
; 5.30

错误信息

Execution error (ClassCastException) at clojure.partial.map/convert-seq-of-int-to-strings.
class clojure.lang.LazySeq cannot be cast to class clojure.lang.IFn

(clojure.lang.LazySeq and clojure.lang.IFn are in unnamed module of loader 'app')

问题分析

  1. 正则表达式错误:原正则#"\d+\d+(\d+)?\.(\d+)?"要求至少两个数字开头,无法匹配单个数字(如输入中的1),且返回的是匹配分组而非完整数字字符串,正确的正则应为#"\d+(\.\d+)?",用于匹配整数或小数格式的数字。
  2. 变量引用错误:代码中new-line和new-seq未定义,应分别改为user-input和new-sequence。
  3. 分区与转换逻辑错误:
    • 使用partition-all 2对3个元素的序列分区完全没必要,直接按位置取元素即可。
    • take 1 new_partition返回的是包含分区的嵌套序列(如((12 1))),此时map-one是一个LazySeq,后续(concat (map-one map-two))错误地将map-one当作函数调用,导致类型转换异常。

修复后的代码

(ns clojure.partial.map
  (:gen-class))

; 匹配整数或小数的正则,返回完整数字字符串序列
(defn string-to-list [s]
  (re-seq #"\d+(\.\d+)?" s))

(defn convert-and-print [ss]
  (let [[num1 num2 num3] ss ; 解构序列为三个元素
        int1 (Integer/parseInt num1)
        int2 (Integer/parseInt num2)
        double1 (Double/parseDouble num3)
        result-list [int1 int2 double1]] ; 存入列表
    (doseq [item result-list]
      (println item))))

(def user-input (read-line))

(def new-sequence (string-to-list user-input))

(convert-and-print new-sequence)

验证结果

输入12 1 5.30后,输出符合预期:

12
1
5.3

内容的提问来源于stack exchange,提问作者ArbIn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 18:15:38