Skip to content

Instantly share code, notes, and snippets.

@kongliangzhong
Last active October 5, 2015 11:48
Show Gist options
  • Save kongliangzhong/2802797 to your computer and use it in GitHub Desktop.
Save kongliangzhong/2802797 to your computer and use it in GitHub Desktop.
jvm base langs stuff
##### SCALA LANGUAGE #####
1) Can someone tell me why this does not work?
case class XY(enum: MyEnum)
object MyEnum extends Enumeration {
val OP1, OP2 = Value
}
Error: not found: type MyEnum
answer:
This is because MyEnum is an object and objects are singletons.
It's not possible to pass singletons as arguments to case classes,
because that would impose there is more than one instance of this object.
If you want to pass a value of MyEnum (i.e. an enumeration value) use MyEnum.Value:
case class XY(enum: MyEnum.Value)
object MyEnum extends Enumeration { val OP1, OP2 = Value }
After that you can use MyEnum as expected:
val x = XY(MyEnum.OP1)
By the way: A common pattern is to define a type alias,
so you can tweak the code a little bit (i.e. use MyEnum instead of MyEnum.Value and OP1 instead of MyEnum.OP1):
object MyEnum extends Enumeration {
type MyEnum = Value
val OP1, OP2 = Value
}
import MyEnum._
case class XY(enum: MyEnum)
class C {
val x = XY(OP1)
}
2) file read&write
read:
Source.fromFile(fileName).getLines
write:
val out = new java.io.PrintWriter(new java.io.File(fileName))
try { out.print(content) } finally {out.close()}
###########################
##### JAVA LANGUAGE BASIC #####
## java package:
java包命名机制:在SystemClassLoader中会对java的包命名有校验,对于以java.开头的用户自定义类,会抛出异常。其他的没有限制。
另外,java编译时对源文件的存放位置并没有做要求,因此,你可以将package javax的源文件放在com.XXX.XX.test包下,但是编译后class文件会在javax目录下。
但是将源文件放在相应的目录下显然是很好的代码组织方式。
## java native2ascii
escape properties file: // utf-8 is the charset of properties file.
native2ascii -encoding utf-8 source.properties dest.properties
## Class.getResourceAsStream and ClassLoader.getResourceAsStream compare:
Class.getResource can take a "relative" resource name, which is treated relative to the class's package. Alternatively you can specify an "absolute" resource name by using a leading slash. Classloader resource paths are always deemed to be absolute.
So there are basically equivalent:
foo.bar.Baz.class.getResource("xyz.txt");
foo.bar.Baz.class.getClassLoader().getResource("foo/bar/xyz.txt");
And so are these (but they're different to the above :)
foo.bar.Baz.class.getResource("/data/xyz.txt");
foo.bar.Baz.class.getClassLoader().getResource("data/xyz.txt");
## show java defualt flags:
java -XX:+PrintFlagsFinal -version
Look for the options MaxHeapSize (for -Xmx) and InitialHeapSize for -Xms:
java -XX:+PrintFlagsFinal -version | grep HeapSize
###############################
##### CLOJURE LANGUAGE STUFF #####
### language basics
-- def/deref
(def visitors (atom #{}))
(swap! visitors conj "Jack")
(deref visitors) / @visitors
-- require/use
(require 'examples.introduction)
(take 10 examples.introdunction/fibs)
(refer 'examples.introducntion)
(take 10 fibs)
(use 'examples.introduction)
(take 10 fibs)
(use :reload 'examples.introduction)
-- apply
(str (interleave "1234" "abcd"))
(apply str (interleave "1234" "abcd"))
(apply str (take-nth 2 "1a2b3c4d"))
-- map
(def inventors {"Lisp" "McCarthy", "Clojure" "Hickey"})
(inventors "Lisp")
(get inventors "Lisp" "default")
;; use keyword:
(def inventors {:Lisp "McCarthy", :Clojure "Hickey"})
-- record
(defrecord Book [title author])
(->Book "Effective Java" "Joshua Bloch")
(Book. "Effective Java" "Joshua Bloch")
(#user.Book{:title "Effective Java", :author "Joshua Bloch"})
-- functions
(defn name doc-string? attr-map?
([params*] body)+)
-- &
define any number of optional params after &.
(defn date [person-1 person-2 & chaperones]
(println person-1 "and" person-2
"went out with" (count chaperones) "chaperones."))
-- anonymous-functions
(fn [params*] body)
(defn indexale-word? [word]
(> (count word) 2))
(filter indexale-word? (str/split "A fine day it is" #"\W+"))
(filter (fn [x] (> (count x) 2)) (str/split "A fine day it is" #"\W+"))
(filter #(> (count %) 2) (str/split "A fine day it is" #"\W+"))
(defn indexale-words [text]
(let [indexale-word? (fn [w] (> (count w) 2))]
(filter indexale-word? (str/split text #"\W+"))))
## variant, bindings and namespace
-- var
(var foo)
#'foo
-- bindings
(let [bindings*] exprs*)
(let [[_ _ z] [1 2 3]]
z)
(let [top (+ bottom size)
right (+ left size)]
[[bottom left] [top left] [top right] [bottom right]]))
-- namespace
(reslove 'foo)
(in-ns 'user)
(ns name& references)
(ns demo.core
(:require [clojure.string :as str])
(:import (java.io File InputStream))
)
## condition and loop clause
-- if
(defn is-small? [num]
(if (< num 100) "yes"
(do
(println "saw a big number" num)
"no")))
-- loop/recur
### seqs
## first/rest/cons
(first aseq)
(rest aseq)
(cons elem aseq)
(seq coll)
(next aseq) == (seq(rest aseq))
(class sym)
coll: #{:a :b :c}
(sorted-set& elements)
(sorted-map& elements)
(conj coll element & elements)
(into to-coll from-coll)
## create seqs
(range start? end step?)
(repeat n x)
(iterate f n) ;; (iterate inc 1)
(take n sequence)
(cycle coll)
(interleave& colls)
(interpose separator coll)
(apply str (interpose separator coll)) == (clojure.string/join separator coll)
(use '[clojure.string :only (join)])
(list & elements)
(vector & elements)
(hash-set & elements)
(hash-map key-1 value-1 ...)
(set coll)
(vec coll)
## filter seqs
-- filter
(filter pred coll)
(take 10 (filter even? (iterate inc 1)))
-- take-while/drop-while
(take-while pred coll)
(take-while (complement #{\a\e\i\o\u}) "the-quick-brown-fox")
-- split-at/split-with
(split-at index coll)
(split-with pred coll)
## seqs pred
-- every?
(every? pred coll)
(every? odd? [1 3 5])
-- some
(some pred coll)
-- not-every?/not-any?
(not-every? pred coll)
(not-any? pred coll)
## transform seqs
-- map
(map f coll)
(map #(format "<%s>%s<%s>" %1 %2 %1) [h1 h2 h3 h1] '("the" "quick" "brown" "fox"))
-- reduce
(reduce f coll)
-- sort/sort-by
(sort comp? coll)
(sort-by a-fn comp? coll)
-- for
(for [binding-form coll-expr filter-expr? ...] expr)
(take 10 (for [n (iterate inc 1) :when (even? n)] n))
(for [n (iterate inc 1) :while (even? n)] n)
(for [file "ABCDEFGH" rank (range 1 9)] (format "%c%d" file rank))
## use java collections as seqs
## regex
-- re-matcher/re-find
(let [m (re-matcher #"\w+" "the quick brown fox")]
(loop [match (re-find m)]
(when match
(println match)
(recur (re-find m)))))
-- re-seq
(re-seq regexp string)
(re-seq #"\w+" "the quick brown fox")
## io
-- reader
(use '[clojure.java.io :only (reader)])
(with-open [rdr (reader "src/demo/core.clj")]
(count (filter #(re-find #"\S" %) (line-seq rdr)))
-- xml-seq
(use '[clojure.xml :only (parse)])
(xml-seq (parse (java.io.File. "src/demo/temp.xml")))
### Functional Programming
##################################
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment