Skip to content

Instantly share code, notes, and snippets.

View kmizu's full-sized avatar

Kota Mizushima kmizu

View GitHub Profile
object BadStack {
class Stack[+A](elements: List[A]) {
def this() { this(Nil) }
def isEmpty: Boolean = elements == Nil
//push1 doesn't compile because the compiler cannot guarantee type safety.
//def push1(e: A): Stack[A] = new Stack(e::elements)
//push2 compiles.
def push2[B >: A](e: B): Stack[B] = new Stack(e::elements)
def pop: (A, Stack[A]) = elements match {
case x::xs => (x, new Stack(xs))
import java.io._
object FileIO {
abstract sealed class AccessMode
case class READ() extends AccessMode
case class WRITE() extends AccessMode
case class READ_WRITE() extends AccessMode
abstract sealed class StreamType
case class BYTES() extends StreamType
case class CHARS() extends StreamType
def sublistN[T](list: List[T], n: Int): List[List[T]] = {
(1 until n).foldLeft((List[List[T]](), list)) {
case ((xs, y::ys), _) => (xs:::List(List(y)), ys)
case ((xs, Nil), _) => (xs:::List(List[T]()), Nil)
} match { case (xs, ys) => xs:::List(ys) }
}
println(sublistN(List(34, 11, 23, 1, 9, 83, 5), 3))
println(sublistN(List(32, 11), 3))
println(sublistN(List(32), 3))
object X extends Enumeration {
val A, B, C = Value
}
val x: X.Value = X.A
x match { case X.A => println("FOO") }
-- Scala --
object X extends Enumeration { val A, B, C = Value }
object Y extends Enumeration { val A, B, C = Value }
var x: X.Value = X.A // これはOK
x = Y.A これはダメ
同じように
-- Java --
enum X { A, B, C }
enum Y { A, B, C }
def foo() { println("foo") }
class A {
def bar() {
foo
}
}
new A().bar()
def removeFirst[A](l: List[A])(f: A => Boolean): List[A] = {
l.foldLeft((List[A](), false)) {
case ((r, found), e) => if((!found) && f(e)) (r, true) else (e::r, found)
}._1.reverse
}
println(removeFirst(List(1, 2, 1))(_ == 3)) // List(1, 2, 1)
println(removeFirst(List(1, 2, 1))(_ == 2)) // List(1, 1)
println(removeFirst(List(1, 2, 1))(_ == 1)) // List(2, 1)
-- Haskell Quiz http://blog.hackers-cafe.net/2010/06/haskell-quiz.html の答えっぽいもの
-- Preludeの$とコンフリクトするので隠す
import Prelude hiding (($))
-- Showのような独自型クラスMyShowを定義
class MyShow a where
myShow :: a -> String
instance MyShow Bool where
myShow arg = "True"
instance MyShow Int where
myShow arg = show arg
def hasA(s: String): Boolean = {
def hasA(i:int, s:String):boolean = {
if(i == s.length) return false
if(s(i) == 'a') return true
return hasA(i + 1, s)
}
hasA(0, s)
}
hasA("abc")
public class Foreach {
public static void main(String[] args) {
int j = 0;
Runnable[] rs = new Runnable[3];
for(final int i:new int[]{3, 5, 7}) {
rs[j] = new Runnable() {
public void run() {
//別々のiをキャプチャーしているか?
System.out.println(i);
}