Functions and casting in clojure

1

I'm starting with Clojure and I have this problem: I need to enter two numbers on the keyboard and compare which is the largest or if they are the same. It gives me a casting error and neither does it read the function with the values I entered by keyboard. Take this from Python to Clojure:

Python

def max (n1, n2):
    if n1 < n2:
       print n2
    elif n2 < n1:
       print n1
    else:
       print "They are equals."

Clojure

(import '(java.util Scanner))
(def scan (Scanner. *in*))
(println "Numero 1: ")
(def num1 (.nextLine scan))
(println "Numero 2: ")
(def num2 (.nextLine scan))
(Integer/parseInt num1)
(Integer/parseInt num2)
(print "Tu numero1 = " num1  "y tu numero2 = " num2)



(defn max [num1 num2]
(if (< num1 num2)
(println "Mayor:" num2)  
(println "Mayor:" num1)
 ))

I need Clojure to work just like in Python.

    
asked by Michelle 06.06.2018 в 19:30
source

1 answer

2

(Integer/parseInt num1) does not change num1 . Because the numbers are immutable, you must link the past number to a new variable. This is how I would write what you are trying to do:

(import '(java.util Scanner))

(defn max [num1 num2]
  (if (< num1 num2)
    (println "Mayor:" num2)
    (println "Mayor:" num1)))

(let [scanner (Scanner. *in*)
      _ (println "Numero 1: ")
      num1 (.nextLine scanner)

      _ (println "Numero 2: ")
      num2 (.nextLine scanner)

      parsed-num1 (Integer/parseInt num1) ; aquí
      parsed-num2 (Integer/parseInt num2)] ; y aquí

  (println "Tu numero1 =" parsed-num1  "y tu numero2 = " parsed-num2)
  (max parsed-num1 parsed-num2))

I made some other changes:

  • I changed from using def to let . let should always be preferred.
  • max is a built-in function. Avoid creating your own functions with built-in names.

(Note, I do not know Spanish, I'm sorry if Google Translate spits something weird.)

    
answered by 06.06.2018 в 20:54