2008-12-08から1日間の記事一覧

Folding

Scala scala> def sum(lst: List[Int]) = (0 /: lst) ((x,y) => x+y) sum: (List[Int])Int scala> sum(List(1,2,3,4)) res10: Int = 10 ruby >> def sum(array) >> array.inject(0) {|sum,x| sum+x } >> end => nil >> sum([1,2,3,4]) => 10 Scala scala> de…

Tuples

Use methods _1 _2 etc. to access members (not zero-based!) ("Hello", 1729)._2 //is 1729 ふーん、なんで0からでないんだろう? scala> ("Hello",22,isEven) res9: (java.lang.String, Int, (Int) => Boolean) = (Hello,22,<function>)</function>

Methods with Function Parameters

Scala scala> val isEven = (x: Int) => x%2 == 0 isEven: (Int) => Boolean = <function> scala> List(2,3,5,7).partition(isEven) res8: (List[Int], List[Int]) = (List(2),List(3, 5, 7)) Ruby >> [2,3,5,7].partition {|x| x % 2 == 0 } => [[2], [3, 5, 7]]</function>

Access by Position

# () are used for indexed access—not [] List(17, 29)(1) //is 29 違和感の原因を一個発見。[]使いたくなる。慣れの問題ですな。

A Random Number List

depricationが出てらー。 scala> def randList(len: Int,n:Int)={ | val gen = new Random | 1 to len map((x:Int) => gen.nextInt(n)) | } warning: there were deprecation warnings; re-run with -deprecation for details randList: (Int,Int)RandomAcce…

Categories of List Methods

* Basic methods length head tail isEmpty * Operators :: ::: + - -- == != >= * Access by position (n) take drop dropRight slice indexOf lastIndexOf * Methods with unary predicates count exists dropWhile filter find findIndexOf forall partit…

Scalaでリファレンスからメソッド引く場合の定石

分かってるメソッド引く場合じゃなくて、こんな事出来るメソッド〜と当たりを付けたい場合。普通みんなどうしてるんだろう? Webのリファレンスで? EclipseやNetBeansで、補完候補表示させてそこから?RubyやRailsはhtml helpファイル(*.chm)で引いてて、割…

Application: Event Handling

scala> import java.awt._ import java.awt._ scala> import java.awt.event._ import java.awt.event._ scala> import javax.swing._ import javax.swing._ scala> implicit def mekeAction(action:(ActionEvent) =>Unit) = new ActionListener { | overrid…

Capturing the Enclosing Environment

scala> val n = 3 n: Int = 3 scala> val fun = (x:Int) => n *x fun: (Int) => Int = <function> scala> fun(2) res0: Int = 6 scala> def mulBy(n : Int) =(x:Int) => n * x mulBy: (Int)(Int) => Int scala> val quadruple = mulBy(4) quadruple: (Int) => Int = <function> s</function></function>…

/: :\

foldLeft っぽいやつと foldRight のエイリアス?