開発環境
- OS X Mavericks - Apple (OS)
- Dart Editor (開発環境)
- Dartium | Dart/ Structured web apps (ブラウザ, Dart VM 用 (Chromium with the Dart VM))
- Safari (ブラウザ, JavaScript 用)
- Dart (プログラミング言語)
Real World Haskell―実戦で学ぶ関数型言語プログラミング(Bryan O'Sullivan (著)、 John Goerzen (著)、 Don Stewart (著)、山下 伸夫 (翻訳)、伊東 勝利 (翻訳)、株式会社タイムインターメディア (翻訳)、オライリージャパン)の4章(関数プログラミング)、4.5(リストを使う)、練習問題 1.をDartで考えてみる。
その他参考書籍
- What is Dart? [Kindle版] (O'Reilly Media) Kathy Walrath Seth Ladd (著) このブログでの感想
練習問題 1.
コード
sample.dart
import 'dart:html';
void main(){
run.onClick.listen((MouseEvent event){
pre.text = window.navigator.userAgent + '\n';
try{
for(List x in [l, e]){
pre.text += 'List: $x\n';
pre.text += ' first: ${x.first}\n';
pre.text += ' last: ${x.last}\n';
}
}catch(e){
pre.text += '$e\n';
}
try{
for(SafeList x in [sl, se]){
pre.text += 'SafeList: $x\n';
pre.text += ' first: ${x.first}\n';
pre.text += ' tail: ${x.tail()}\n';
pre.text += ' last: ${x.last}\n';
pre.text += ' init: ${x.init()}\n';
}
}catch(e){
pre.text += '$e\n';
}
});
clear.onClick.listen((MouseEvent event) => pre.text = '');
}
ButtonElement run = querySelector('#run_dart');
ButtonElement clear = querySelector('#clear');
PreElement pre = querySelector('#pre0');
List l = [1, 2, 3, 4, 5];
List e = [];
SafeList sl = new SafeList(l);
SafeList se = new SafeList(e);
// firstとlastがエラーにならないような定義
// tail method, init methodを追加
class SafeList{
List sequence;
var first;
var last;
SafeList(List sequence){
this.sequence = sequence;
if(sequence.isNotEmpty){
first = sequence.first;
last = sequence.last;
}
}
SafeList tail() => sequence.isNotEmpty ?
new SafeList(sequence.sublist(1)) : null;
SafeList init() => sequence.isNotEmpty ?
new SafeList(sequence.sublist(0, sequence.length -1)) : null;
String toString() => sequence.toString();
}
0 コメント:
コメントを投稿