Skip to content

Instantly share code, notes, and snippets.

@himerzi
Last active December 27, 2015 12:39
Show Gist options
  • Save himerzi/7327649 to your computer and use it in GitHub Desktop.
Save himerzi/7327649 to your computer and use it in GitHub Desktop.
Clojure Session 1 Exercise
(ns d1.core (:gen-class))
(use 'clojure.java.io)
;;To run these examples:
;; lein repl
;; user=> (require 'd1.core)
;; to call main
;; user=> (d1.core/-main)
(defn n-random
"I return a vector of N random numbers"
[n]
(vec (repeatedly n #(rand-int (rand-int 1000))))
)
(defn n-random-vectors
"I return a vector of N random of N numbers"
[n]
(vec (repeatedly n #(n-random n))))
(defn write
"I write to a file"
[v]
(spit "/tmp/test.txt" (str v "\n") :append true)
)
(defn write-vector
"I write a vector to a file"
[v]
(dorun (map write v))
)
(defn read-vector
"I read the vector from a file"
[f-name]
(with-open [rdr (reader "/tmp/test.txt")]
(into [] (doall (map read-string (line-seq rdr))))
)
)
;; Stats calculation
(defn avg
"I calculate the average"
[v]
(/ (reduce + v) (count v))
)
(defn avgavg
"average of all the numbers in a vector of vectors"
[v]
(avg (map avg v))
)
(defn -main
""
[]
(
(println "writing vectors to file")
(spit "/tmp/test.txt" "")
(write-vector (n-random-vectors 3))
(println "reading vectors from file")
(println (read-vector "/tmp/test.txt"))
(println "Doing some Maths")
(println "... The average is")
(println (avgavg (read-vector "/tmp/test.txt")))
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment