ラベル Erlang の投稿を表示しています。 すべての投稿を表示
ラベル Erlang の投稿を表示しています。 すべての投稿を表示

2012年1月14日土曜日

Erlang 配列による線形探索


アルゴリズムの勉強で線形探索をやっている。
cで作ったけど、Erlangでも作ってみた。
ソースを記載しておく。

こういったものはGitHubに置くべきだと思う。今セッティング中...

【ソース】
----- ここから -----
%% -------------
%% linear_search of array
%% -------------

-module(linear_search).
-export([search2_2_1/2]).
-ifdef(test).
-include_lib("eunit/include/eunit.hrl").
-endif.

% 表の線形探索
% @spec search2_2_1(Array,Target) -> {true,pos} | false
search2_2_1(Array,Target) ->
        i_search2_2_1(Array,Target,0).

% @spec i_search2_2_1(Array,Target,Index) ->{true,pos} | false
i_search2_2_1(Array,Target,Index) when Index < size(Array) ->
        X = array:get(Index,Array),
        if
               X =:= Target -> {true,Index};
               true -> i_search2_2_1(Array,Target,Index + 1)
       end;
i_search2_2_1(Array,Target,Index) when Index >= size(Array) ->
        false.

-ifdef(test).
-define(FUNC(X,Y),search2_2_1(X,Y)).
-define(AL(),(array:from_list( [1,3,4] ))).
m1_test() -> ?FUNC(?AL(),1) =:= 0.
m2_test() -> ?FUNC(?AL(),3) =:= 1.
m3_test() -> ?FUNC(?AL(),4) =:= 2.
m4_test() -> ?FUNC(?AL(),2) =:= false.
-endif.
----- ここまで -----
次は、2分探索をErlangで書いてみたい。

Erlang Eunit の 簡単な勉強

Eunitでテスト駆動開発したくて、勉強した。
参考:
shibu.jp: EUnitユーザーズガイド : http://articles.shibu.jp/category/777978-1.html

まず、上記サイトを参考にして、プログラム書いてみた。

【ソース】
----- ここから -----

-module(test_eunit).
-include_lib("eunit/include/eunit.hrl").
%-export([start/0]).
-define(TEST(X),reverse_X_test()).

-ifdef(debug).
%start() ->
%        reverse_test(),
%        ?TEST(nil),
%        reverse_one_test(),
%        reverse_two_test(),
%        reverse_ng_test().

% 任意の値を返すとテストは成功とみなされる。
% なんらかの例外を投げる場合には失敗したとみなされる。
reverse_test() -> lists:reverse([1,2,3]).

?TEST(nil) -> [] = lists:reverse([]).
reverse_one_test() -> [1] = lists:reverse([1]).
reverse_two_test() -> [2,1] = lists:reverse([1,2]).
reverse_ng_test() -> [1,1] = lists:reverse([1,2]).

-endif.
----- ここまで -----

これをコマンドプロンプト上から実行した。
【コマンドプロンプト】
$> C:\Users\andre\ework>erlc -Ddebug test_eunit.erl

$> C:\Users\andre\ework>erl -noshell -run test_eunit test -run init stop
test_eunit: reverse_ng_test...*failed*
::error:{badmatch,[2,1]}
  in function test_eunit:reverse_ng_test/0


=======================================================
  Failed: 1.  Skipped: 0.  Passed: 4.


ソース上はコメントアウトされているが、start()から全テストプログラムを実行しなくていい。それが素晴らしい!

単に、xx_test()と関数名の最後にtestと付けただけで、Eunitはテスト関数だと認識してくれて、実行し、実行結果を出してくれる。いい!

defineは気にしないでX-(

Erlang arrayモジュール まとめ(size,sparse_size)

今日は、sizeとsparse_sizeについて。

■size/1
[構文]
size(Array :: array()) -> integer() >= 0
  array内のエントリの数を返す。エントリは0からsize(Array)-1まで。

■sparse_size/1
[構文]
sparse_size(A::array()) -> integer()
  うまく訳せない。

実行例)

Erlang R14B01 (erts-5.8.2) [smp:2:2] [rq:2] [async-threads:0]

Eshell V5.8.2  (abort with ^G)
1> D0 = [{0,1},{1,2},{4,9}].
[{0,1},{1,2},{4,9}]
5> A0 = array:from_orddict(D0,0).
{array,5,10,0,{1,2,0,0,9,0,0,0,0,0}}
7> A1 = array:set(6,0,A0).
{array,7,10,0,{1,2,0,0,9,0,0,0,0,0}}
8> array:size(A1).
7
9> array:sparse_size(A1).
5

2012年1月12日木曜日

Erlang arrayモジュール まとめ(to_list,to_orddict,sparse_to_list,sparse_to_orddict)

to_list,to_orddict,sparse_to_list,sparse_to_orddictを一気に。

注目は
to_listとsparse_to_orddictの違い

to_orddictとsparse_to_orddictの違い

■to_orddict(Array::array()) -> [{Index::integer(), Value::term()}]
 arrayから{Index,Value}型のオーダーリストへ変換する。

■to_list(Array::array()) -> list()
 arrayからリストへ変換する。

■sparse_to_orddict(Array::array()) -> [{Index::integer(), Value::term()}]
 arrayから{Index,Value}型のオーダーリストへ変換する。ただし、初期値はスキップする。

■sparse_to_list(Array::array()) -> list()
 arrayからリストへ変換する。ただし、初期値はスキップする。

【実行例】

Erlang R14B01 (erts-5.8.2) [smp:2:2] [rq:2] [async-threads:0]

Eshell V5.8.2  (abort with ^G)
1> L1 = [3,2,6,7].
[3,2,6,7]
2> A0 = array:from_list(L1).
{array,4,10,undefined,
       {3,2,6,7,undefined,undefined,undefined,undefined,undefined,
        undefined}}
4> A1 = array:set(5,5,A0).
{array,6,10,undefined,
       {3,2,6,7,undefined,5,undefined,undefined,undefined,
        undefined}}

8> A3 =
8>
8> array:set(9,0,A1).
{array,10,10,undefined,
       {3,2,6,7,undefined,5,undefined,undefined,undefined,0}}

11> array:sparse_to_list(A3).
[3,2,6,7,5,0]
12> array:sparse_to_list(A1).
[3,2,6,7,5]
13> array:sparse_to_orddict(A3).
[{0,3},{1,2},{2,6},{3,7},{5,5},{9,0}]
14> array:sparse_to_list(A2).
[3,2,6,7]
15> array:to_list(A3).
[3,2,6,7,undefined,5,undefined,undefined,undefined,0]
16> array:to_orddict(A3).
[{0,3},
 {1,2},
 {2,6},
 {3,7},
 {4,undefined},
 {5,5},
 {6,undefined},
 {7,undefined},
 {8,undefined},
 {9,0}]

Erlang arrayモジュール まとめ(map)

今日はarray:mapについて

■map/2
【構文】
map(Function, Array::array()) -> array()

 arrayの各値に対して、Functionを実行する。Indexの低い方から順に。
Functionが関数でない場合、badargエラーである。

【実行例】

1> L1 = [{1,3},{2,4},{3,6}].
[{1,3},{2,4},{3,6}]
3> A1 = array:from_orddict(L1,0).
{array,4,10,0,{0,3,4,6,0,0,0,0,0,0}}
4> Fun = fun(Index,Value) -> Index + Value end.
#Fun<erl_eval.12.113037538>
5> array:map(Fun,A1).
{array,4,10,0,{0,4,6,9,0,0,0,0,0,0}}
6>

2012年1月11日水曜日

Erlang arrayモジュール まとめ(from_orddict)


arrayモジュールのfrom_orddict関数について

なんと、{Key,Value}型を値とするリストをarrayプロセスにしてしまう。

■from_orddict(Orddict::list()) -> array()
    from_list(List, undefined)と同等

■from_orddict(List::list(), Default::term()) -> array()

  リストをarrayに変換する。初期値はDefaultの値。Listがリストでない場合、badargエラーである。

【実行例】
1> L0 = [{0,3},{1,4},{2,6}].
[{0,3},{1,4},{2,6}]
2> array:from_orddict(L0).
{array,3,10,undefined,
       {3,4,6,undefined,undefined,undefined,undefined,undefined,
        undefined,undefined}}
3> array:from_orddict(L0,0).
{array,3,10,0,{3,4,6,0,0,0,0,0,0,0}}
4> L1 = L0 ++ [{5,7},{10,9}].
[{0,3},{1,4},{2,6},{5,7},{10,9}]
5> array:from_orddict(L1).
{array,11,100,undefined,
       {{3,4,6,undefined,undefined,7,undefined,undefined,undefined,
         undefined},
        {9,undefined,undefined,undefined,undefined,undefined,
         undefined,undefined,undefined,undefined},
        10,10,10,10,10,10,10,10,10}}
6> array:from_orddict(0).
** exception error: bad argument
     in function  array:from_orddict/2

Erlang arrayモジュール まとめ(foldl)

今日は、arrayモジュールのfoldlについて

foldは英語で折りたたむという意味。
よって、arrayプロセス内の値を引数に与えられたFunctionで計算して、1つの値を出力する。

foldlのlはleftなので、arrayのindex = 0から順に計算する。

■foldl(Function, InitialAcc::term(), Array::array()) -> term()

 Function = (Index::integer(), Value::term(), Acc::term()) -> term()

初期値と与えられたFunctionを使用し、arrayの値をFoldする。値はインデックスの低いほうから、高い方へ順に移動する。

もし、Functionが関数でない場合、badargエラーとなる。

【実行例】
1> A0 = [1,2,3,4,5].
[1,2,3,4,5]
2> A1 = array:from_list(A0,0).
{array,5,10,0,{1,2,3,4,5,0,0,0,0,0}}
3> Fun = func(Index,Value,Sum) -> Index + Sum end.
* 1: syntax error before: '->'
3> Fun = fun(Index,Value,Sum) -> Index + Sum end.
#Fun<erl_eval.18.105910772>
4> array:foldl(Fun,0,A1).
10
5> array:foldl(Fun,1,A1).
11
6> FunB = fun(Index,Value,Sum) -> Value + Sum end.
#Fun<erl_eval.18.105910772>
7> array:foldl(FunB,0,A1).
15

2012年1月10日火曜日

Erlang arrayモジュール まとめ(from_list)

夜も遅いので、軽いやつを。
リストからarrayモジュールへの変換関数。

■from_list/1
【構文】
from_list(List :: list()) -> array()
→from_list(List,undefined)と等しい。

【実行例】
18> L0 = [1,2,3,4].
[1,2,3,4]
19> array:from_list(L0).
{array,4,10,undefined,
       {1,2,3,4,undefined,undefined,undefined,undefined,undefined,
        undefined}}

■from_list/2
【構文】
from_list(List :: list(), Default :: term()) -> array()
→リストから拡張可能arrayモジュールへ変換します。第2引数のDefaultはarrayモジュールの初期化されていない部分の初期値に使われる。第1引数のListがリストじゃなければ、badargエラーを返す。

【実行例】
18> L0 = [1,2,3,4].
[1,2,3,4]
23> A1= array:from_list(L0,0).
{array,4,10,0,{1,2,3,4,0,0,0,0,0,0}}

■from_list/1 と from_list/2 の違い
初期値がundefinedかオプションのものか。

■その他
見てわかるとおり、初期Maxサイズは10みたい。


メモ:
実はfoldl/3の実行例を作成しようとしていたんだけど、まだちょっとよくわからないのと、いい例が見つからない。


2012年1月9日月曜日

Erlang arrayモジュール まとめ(set,relax,fix)

arrayモジュールのまとめ set,relax,fix編

■set/3
【構文】
set(I :: array_indx(), Value :: term(), Array :: array()) -> array()

インデックス I に対して、Valueを設定する。
以下の場合はエラー:badargを返す。
  1. インデックス I が負の値
  2. arrayプロセスがfixedであり、インデックス I が最大サイズ以上のとき

arrayプロセスがfixedでなく、インデックス I がsize(Array)-1より大きい場合は、arrayプロセスはI+1サイズに拡張される。

■relax/1
【構文】relax(Array::array()) -> array()

arrayプロセスを拡張可能にする。

■fix/1
【構文】fix(Array::array()) -> array()

arrayプロセスを固定サイズに設定する。arrayプロセスが自動的に拡張されることを防ぐ。

実行例)
3> A1 = array:new(2).
{array,2,0,undefined,10}               % arrayプロセス生成
4> A2 = array:set(1,2,A1).            % index = 1 に value = 2 を設定
{array,2,0,undefined,
       {undefined,2,undefined,undefined,undefined,undefined,
                  undefined,undefined,undefined,undefined}}
5> A3 = array:set(0,3,A2).            % index = 0 に value = 3 を設定
{array,2,0,undefined,
       {3,2,undefined,undefined,undefined,undefined,undefined,
        undefined,undefined,undefined}}
6> A4 = array:set(2,3,A3).            % index = 2 に value = 3 を設定 → fixedのためbadargエラー
** exception error: bad argument
     in function  array:set/3

8> array:is_fix(A3).                        % fixedかどうか調べる
true

10> A4 = array:relax(A3).             % 拡張可能にする
{array,2,10,undefined,
       {3,2,undefined,undefined,undefined,undefined,undefined,
        undefined,undefined,undefined}}
11> array:fix(A4).                          % fixedする
{array,2,0,undefined,
       {3,2,undefined,undefined,undefined,undefined,undefined,
        undefined,undefined,undefined}}

12> array:set(2,5,A4).                   % index = 2 に value = 5 を設定 → 拡張可能なため、OK。
{array,3,10,undefined,                   % arrayプロセスのサイズが 3 (= I + 1)となっている
       {3,2,5,undefined,undefined,undefined,undefined,undefined,
        undefined,undefined}}
13> array:set(11,5,A4).                 % index = 11 に value = 5 を設定 → 拡張可能なため、OK
{array,12,100,undefined,               % arrayプロセスのサイズが 12 (= I + 1)となっている
       {{3,2,undefined,undefined,undefined,undefined,undefined,
         undefined,undefined,undefined},
        {undefined,5,undefined,undefined,undefined,undefined,
                   undefined,undefined,undefined,undefined},
        10,10,10,10,10,10,10,10,10}}


Erlang arrayモジュール まとめ(array:default)

今日は、arrayモジュールのdefaultについて。

defaultの構文は以下のとおり。
【構文】
default(Array::array()) -> term()

実行例)
5> A2 = array:new(5,{default,0}).
{array,5,0,0,10}
15> array:default(A2).
0

11> A5 = array:new(4,{default,4}).
{array,4,0,4,10}
12> array:default(A5).
4

1> A0 = array:new(5).
{array,5,0,undefined,10}
2> array:default(A0).
undefined

上記の実行例の赤文字の部分が返却される。
arrayプロセスを生成したときに、オプションで設定したdefaultの値が返ってくる。
オプション設定していなければ、undefinedが返ってくる。

2012年1月8日日曜日

Erlang arrayモジュール まとめ(array:new)

Erlangのarrayモジュールについて、ちょっと書きたいと思う。

R14B01のarrayモジュール一覧を下記に示す。

default/1            fix/1                foldl/3            
foldr/3              from_list/1          from_list/2        
from_orddict/1       from_orddict/2       get/2              
is_array/1           is_fix/1             map/2              
module_info/0        module_info/1        new/0              
new/1                new/2                relax/1            
reset/2              resize/1             resize/2          
set/3                size/1               sparse_foldl/3    
sparse_foldr/3       sparse_map/2         sparse_size/1      
sparse_to_list/1     sparse_to_orddict/1  to_list/1          
to_orddict/1      

今回はnew関数について、ドキュメントを参照しつつ、Eshell?で動かしてみた。

■new/0
new()->array()

【説明】
arrayプロセスの新規生成。サイズは0。サイズを拡張可能。

例)
8> A2 = array:new().
{array,0,10,undefined,10}
9> A2.
{array,0,10,undefined,10}
10> array:size(A2).
0

■new/1
new(Options::term()) -> array()

【説明】
オプションの指定に基づいて、arrayプロセスを生成。デフォルトは、拡張可能なサイズ0のもの。indexは0から指定する。

【オプション】
オプションは単一のタプルもしくは複数のタプルのリストで指定可能。

N::integer() or {size, N::integer()}
→arrayの初期サイズ。Nが負の整数の場合、bad argumentエラー(badarg)。


例)
11> A3 = array:new(-1).
** exception error: bad argument
in function array:new_1/4

12> A3 = array:new(0).
{array,0,0,undefined,10}

13> A4 = array:new(4).
{array,4,0,undefined,10}

14> A5 = array:new({size,4}).
{array,4,0,undefined,10}


fixed or {fixed, true}
→固定サイズのarrayプロセスを生成。

例)
20> A8 = array:new([{size,5},{fixed,true}]).
{array,5,0,undefined,10}
23> array:is_fix(A8).
true

27> A9 = array:new().
{array,0,10,undefined,10}
28> array:is_fix(A9).
false

{fixed, false}
→拡張可能なarrayプロセスを生成。

例)
29> A10 = array:new([{size,2},{fixed,false}]).
{array,2,10,undefined,10}

30> array:is_fix(A10).
false

{default, Value}
→初期値Valueのarrayプロセスを生成。
例)
31> A11 = array:new([{size,2},{default,10}]).
{array,2,0,10,10}

33> A12 = array:new({size,2}).
{array,2,0,undefined,10}

■new/2
new(Size::integer(), Options::term()) -> array()

【説明】
オプションとサイズに基づいて、arrayプロセスを新規生成する。
Sizeが負の整数の場合、badargエラーである。
固定サイズで生成される。
注意:オプションでサイズを指定すれば、そのサイズで上書きされ、arrayプロセスが生成される。

例)
35> A13 = array:new([10,{default,0}]).
{array,10,0,0,10}
37> array:set(2,5,A13).
{array,10,0,0,{0,0,5,0,0,0,0,0,0,0}}

38> A14 = array:new(10).
{array,10,0,undefined,10}
39> array:set(2,5,A14).
{array,10,0,undefined,
{undefined,undefined,5,undefined,undefined,undefined,
undefined,undefined,undefined,undefined}}


2012年1月2日月曜日

Erlang queue バイナリとかリストではなくqueue

Erlangでキューってどうやるんだ?という問から検索をかけたら、バイナリでやるとかリストでやるとか出てきた。

え~・・・と思いつつ、放置↔queue検索を繰り返していたら、queueモジュールがあることがわかった。
基本操作だけやってみた。

■queue:new()->queue   ------------------------------------------
空のキューを作成する。

Erlang R14B01 (erts-5.8.2) [smp:2:2] [rq:2] [async-threads:0]
Eshell V5.8.2  (abort with ^G)

1> Q = queue:new().
{[],[]}



■queue:in(term,queue)->queue    ------------------------------------------
第1引数:キューに入れるもの
第2引数:操作対象のキュー
戻り:操作後のキュー

2> Q1 = queue:in(3,Q).
{[3],[]}
・・・
5> Q4 = queue:in(6,Q3).
{[6,5,4],[3]}

■queue:out(queue)->{{value, term}, queue} | {empty, queue}------------------------------------------
第1引数:対象のキュー
戻り:キュー内の先頭の値 もしくは 空({empty, queue})

6> queue:out(Q4).
{{value,3},{[6,5],[4]}}



■queue:in_r(term,queue) -> queue   ------------------------------------------
第1引数:キューの先頭に入れるデータ
第2引数:操作対象のキュー
戻り:操作後のキュー
キューの先頭に値を入れる。

9> Q5 = queue:in_r(7,Q4).
{[6,5,4],[7,3]}


■queue:out(queue)->queue   ------------------------------------------
第1引数:操作対象のキュー
戻り:操作後のキュー

10> queue:out(Q5).
{{value,7},{[6,5,4],[3]}}



■queue:out_r(queue)->queue   ------------------------------------------
第1引数:操作対象のキュー
戻り:操作後のキュー
キューの1番最後から値をとる。

11> queue:out_r(Q5).
{{value,6},{[5,4],[7,3]}}



■queue:from_list(list)->queue   ------------------------------------------
第1引数:リスト
戻り:キュー
 リストからキューを作る。

15> queue:from_list([1,2,3,4,5]).
{[5,4,3],[1,2]}




■queue:to_list(queue) ->list   ------------------------------------------
第1引数:キュー
戻り:リスト


16> queue:to_list(Q5).
[7,3,4,5,6]




■queue:reverse(queue)->queue   ------------------------------------------
第1引数:キュー
戻り:キュー


17> queue:reverse(Q5).
{[7,3],[6,5,4]}



■queue:split(Integer,queue)->{queue,queue}   ------------------------------------------
第1引数:整数
第2引数:キュー
戻り:キューのタプル


20> {Q6,Q7} = queue:split(2,Q5).
{{[3],[7]},{[6,5],[4]}}


21> Q6.
{[3],[7]}
22> Q7.
{[6,5],[4]}


■queue:join(queue,queue)->queue   ------------------------------------------
第1引数:キュー
第2引数:キュー
戻り:キュー


23> queue:join(Q6,Q7).
{[6,5],[7,3,4]}



■queue:filter(fun,queue)->queue  ------------------------------------------
第1引数:関数
第2引数:キュー
戻り:キュー


9> Q5 = queue:in_r(7,Q4).
{[6,5,4],[7,3]}


24> Fun1 = fun(X) -> true end.
#Fun<erl_eval.6.13229925>
25> queue:filter(Fun1,Q5).
{[6,5,4],[7,3]}


26> Fun2 = fun(X) -> false end.
#Fun<erl_eval.6.13229925>
27> queue:filter(Fun2,Q5).
{[],[]}




28> Fun3 = fun(X) -> if X rem 2 == 0 -> true;
28> true -> false end
28> end.
#Fun<erl_eval.6.13229925>
29> queue:filter(Fun3,Q5).                
{[6],[4]}
30> Q5.
{[6,5,4],[7,3]}


■queue:member(term,queue)->boolean   ------------------------------------------
第1引数:データ
第2引数:キュー
戻り:真偽


9> Q5 = queue:in_r(7,Q4).
{[6,5,4],[7,3]}
31> queue:member(3,Q5).
true
32> queue:member(10,Q5).
false


2011年10月19日水曜日

Erlang Dialog setLabel サンプル Sample


タイトルにある通りのサンプル。
Dialogの生成でタイトルを"Target Display"に設定しているが、setLabelで"setLabel"に再設定している。

表示される画面の左上が"setLabel"になっているはず。

ソース:

-module(dialogSetLabel).
-export([start/0]).
%%-export([new/2]). %% API
-include_lib("wx.hrl").

start()->
    Wx = wx:new(),
    Dialog = wx:batch(fun()->new(Wx, 100) end),
    wxWindow:show(Dialog),
    loop(Dialog).

new(Parent,Id)->
    Option = [ { size, {210, 100} } ],
    Head = "Target Display",
    Dialog = wxDialog:new(Parent, Id, Head, Option),
    wxDialog:setLabel(Dialog, "setLabel"),
    wxDialog:connect(Dialog, close_window),

    Dialog.

loop(Dialog)->
    receive
         %% Closeボタン押下時
        #wx{obj = Obj, event = #wxClose{}}->
            io:format("~p Closing window ~n", [self()]),
            wxWindow:destroy(Obj)
    end.

2011年10月18日火曜日

Erlang left click wxMouseEvent Sample サンプル

マウスの左クリックで、画面のテキスト文字列を再設定させるサンプルを書いた。

動作例:


eSample130.erlを実行すると、command Test画面が表示される。

show Windowボタンを押下すると、Target Display画面が表示される。

Target Display画面上の文字列上のテキストを左クリックすると、「Left Click! ~」が画面上に表示される。

下記にソースを表示する。
ダウンロードは以下から。
eSample130.erl:
https://docs.google.com/leaf?id=0B8Fi1kuQJgFrNmE1Yjc3MTYtYjMxOS00NzQyLWI0OTItMWM5NzAyNzU3NWJl&hl=ja

eSample130_1.erl(更新前):
https://docs.google.com/leaf?id=0B8Fi1kuQJgFrYzM4MGE4ZGUtMTU2NS00NzkzLWI4YjYtZGUyMTdlZmM1NTlj&hl=ja

eSample130_1.erl(更新後):
https://docs.google.com/leaf?id=0B8Fi1kuQJgFrYjJkYWI5NDgtNzBkMS00ZWUyLWI0M2YtYzA3ZWYzZjRlNGYx&hl=ja

ソース:

-module(eSample130).
-export([start/0]).
-include_lib("wx.hrl").
-define(wxIDButton, 10).

start()->
    Wx = wx:new(),
    {Frame, Pid} = wx:batch(fun()->create_window(Wx) end),
    wxWindow:show(Frame),
    loop(Pid),
    ok.
%% 画面を表示
create_window(Wx)->
    Option = [ { size, {310, 150 } } ],
    Str = "command Test.",
    Frame = wxFrame:new(Wx,
                        ?wxID_ANY,
                        Str,
                        Option),
    % Set Button On Frame
    %PnlOp = [ {pos, {120, 10}}, {size, {50, 10}}],
    BtnOp = [ {label, "show Window"} ],
    Panel = wxPanel:new(Frame, 120, 10, 50, 10),
    Button = wxButton:new(Panel, ?wxIDButton, BtnOp),
    % Create Status Bar
    wxFrame:createStatusBar(Frame, []),
    wxFrame:setStatusText(Frame, Str),

    %% Dialog生成
    Pid = spawn_link(fun() -> eSample130_1:start() end),

    %% イベントを登録
    wxFrame:connect( Frame, close_window ),%% Closeボタン
    wxButton:connect(Button, command_button_clicked),%% show Windowボタン

    {Frame, Pid}.

loop(Pid)->
    receive
        %% Closeボタン押下時
        #wx{obj = Obj, event = #wxClose{}}->
            io:format("~p Closing window ~n", [self()]),
            wxWindow:destroy(Obj);
        %% ボタン押下時
        #wx{ event = #wxCommand{} } ->
            Pid ! {visible, self()},
            io:format(" Clicked Button ~n"),
            loop(Pid);
        %% Dialogからのメッセージがあった時
        {reply, ok}->
            loop(Pid)
    end.

===============================//================================


-module(eSample130_1).
-export([start/0]).
%%-export([new/2]). %% API
-include_lib("wx.hrl").

start()->
    Wx = wx:new(),
    Dialog = wx:batch(fun()->new(Wx, 100) end),
    loop(Dialog).

new(Parent,Id)->
    Option = [ { size, {210, 100} } ],
    Head = "Target Display",
    Dialog = wxDialog:new(Parent, Id, Head, Option),

    %OPP = [{size,{100,50}}],
    %Panel = wxPanel:new(Parent,OPP),

    Str = "Push close Button.",
    OPST1 = [{pos, {50,10}}],
    ST = wxStaticText:new( Dialog, 1 , Str, OPST1),
    %ST = wxStaticText:new( Panel, 1 , Str, OPST1),

    wxDialog:connect(Dialog, close_window),
    %wxStaticText:connect(ST, left_down),
    wxDialog:connect(Dialog, left_down),
    wxDialog:connect(Dialog, left_up),
    wxDialog:connect(Dialog, middle_down),
    wxDialog:connect(Dialog, middle_up),
    wxDialog:connect(Dialog, right_down),
    wxDialog:connect(Dialog, right_up),
    wxDialog:connect(Dialog, motion),
    wxDialog:connect(Dialog, enter_window),
    wxDialog:connect(Dialog, leave_window),
    wxDialog:connect(Dialog, left_dclick),
    wxDialog:connect(Dialog, middle_dclick),
    wxDialog:connect(Dialog, right_dclick),
    wxDialog:connect(Dialog, mousewheel),
    wxDialog:connect(Dialog, nc_left_down),
    wxDialog:connect(Dialog, nc_left_up),
    wxDialog:connect(Dialog, nc_middle_down),
    wxDialog:connect(Dialog, nc_middle_up),
    wxDialog:connect(Dialog, nc_right_down),
    wxDialog:connect(Dialog, nc_right_up),
    wxDialog:connect(Dialog, nc_motion),
    wxDialog:connect(Dialog, nc_enter_window),
    wxDialog:connect(Dialog, nc_leave_window),
    wxDialog:connect(Dialog, nc_left_dclick),
    wxDialog:connect(Dialog, nc_middle_dclick),
    wxDialog:connect(Dialog, nc_right_dclick),


    Dialog.

%% 閉じるボタン押下時の動作
loop(Dialog)->
    receive
        %% closeボタン押下時
        #wx{event = #wxClose{ type = close_window }}->
            wxDialog:show(Dialog, [{show, false}]),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = left_down}}->
            wxDialog:setLabel(Obj, "left_down!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = left_up}}->
            wxDialog:setLabel(Obj, "left_up!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = middle_down}}->
            wxDialog:setLabel(Obj, "middle_down!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = middle_up}}->
            wxDialog:setLabel(Obj, "middle_up!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = right_down}}->
            wxDialog:setLabel(Obj, "right_down!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = right_up}}->
            wxDialog:setLabel(Obj, "right_up!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = motion}}->
            wxDialog:setLabel(Obj, "motion!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = enter_window}}->
            wxDialog:setLabel(Obj, "enter_window!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = leave_window}}->
            wxDialog:setLabel(Obj, "leave_window!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = left_dclick}}->
            wxDialog:setLabel(Obj, "left_dclick!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = middle_dclick}}->
            wxDialog:setLabel(Obj, "middle_dclick!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = right_dclick}}->
            wxDialog:setLabel(Obj, "right_dclick!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = mousewheel}}->
            wxDialog:setLabel(Obj, "mousewheel!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = nc_left_down}}->
            wxDialog:setLabel(Obj, "nc_left_down!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = nc_left_up}}->
            wxDialog:setLabel(Obj, "nc_left_up!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = nc_middle_down}}->
            wxDialog:setLabel(Obj, "nc_middle_down!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = nc_middle_up}}->
            wxDialog:setLabel(Obj, "nc_middle_up!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = nc_right_down}}->
            wxDialog:setLabel(Obj, "nc_right_down!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = nc_right_up}}->
            wxDialog:setLabel(Obj, "nc_right_up!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = nc_motion}}->
            wxDialog:setLabel(Obj, "nc_motion!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = nc_enter_window}}->
            wxDialog:setLabel(Obj, "nc_enter_window!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = nc_leave_window}}->
            wxDialog:setLabel(Obj, "nc_leave_window!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = nc_left_dclick}}->
            wxDialog:setLabel(Obj, "nc_left_dclick!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = nc_middle_dclick}}->
            wxDialog:setLabel(Obj, "nc_middle_dclick!"),
            loop(Dialog);
        #wx{obj = Obj, event = #wxMouse{ type = nc_right_dclick}}->
            wxDialog:setLabel(Obj, "nc_right_dclick!"),
            loop(Dialog);
        %% 他ウィンドウのボタンが押下された時
        {visible, _From} ->
            %% Dialogを表示する
            wxDialog:show(Dialog, [{show, true}]),
            _From ! {reply, ok},
            loop(Dialog)
    end.

ncがいったい何を指しているのかわからない。



2011年10月16日日曜日

Erlang wxDialog showメソッド 表示/非表示

Java逆引き大全500の極意
http://goo.gl/JBiP9

上記Java本のサンプル129の「フレームウィンドウの表示/非表示を切り替える」というページをErlangで記述してみた。その表示例とソースを以下に掲載する。

表示例:


本サンプルの実行手順は以下。
1.setVisible.erlをコンパイルする。[c(setVisible).]
2.setVisible2.erlをコンパイルする。[c(setVisible2).]
3.[setVisible:start().]を実行すると、setVisible Test.画面(後ろの画面)が表示される。
4.[show Window]ボタンを押下すると、Target Display画面が表示される。
5.Target Display画面の×ボタンを押下すると、Target Display画面が非表示される。
6.setVisible Test.画面の×ボタンを押下すると、setVisible Test.画面が閉じる。

ソース:
setVisible.erl:https://docs.google.com/leaf?id=0B8Fi1kuQJgFrZmJjNzRlY2ItMWJkMC00NTljLWI5NTktYjBhMGFiN2Q4YTE3&hl=ja

setVisible2.erl:https://docs.google.com/leaf?id=0B8Fi1kuQJgFrYTIxMDk0MGYtMWE0ZS00YmI4LWIzMWYtNDUzNTkwY2VlOWZk&hl=ja

setVisible.erl:

-module(setVisible).
-export([start/0]).
-include_lib("wx.hrl").
-define(wxIDButton, 10).

start()->
    Wx = wx:new(),
    {Frame, Pid} = wx:batch(fun()->create_window(Wx) end),
    wxWindow:show(Frame),
    loop(Pid),
    ok.
%% 画面を表示
create_window(Wx)->
    Option = [ { size, {310, 150 } } ],
    Str = "setVisible Test.",
    Frame = wxFrame:new(Wx,
                        ?wxID_ANY,
                        Str,
                        Option),
    % Set Button On Frame
    %PnlOp = [ {pos, {120, 10}}, {size, {50, 10}}],
    BtnOp = [ {label, "show Window"} ],
    Panel = wxPanel:new(Frame, 120, 10, 50, 10),
    Button = wxButton:new(Panel, ?wxIDButton, BtnOp),
    % Create Status Bar
    wxFrame:createStatusBar(Frame, []),
    wxFrame:setStatusText(Frame, Str),

    %% Dialog生成
    Pid = spawn_link(fun() -> setVisible2:start() end),

    %% イベントを登録
    wxFrame:connect( Frame, close_window ),%% Closeボタン
    wxButton:connect(Button, command_button_clicked),%% show Windowボタン

    {Frame, Pid}.

loop(Pid)->
    receive
        %% Closeボタン押下時
        #wx{obj = Obj, event = #wxClose{}}->
            io:format("~p Closing window ~n", [self()]),
            wxWindow:destroy(Obj);
        %% ボタン押下時
        #wx{ event = #wxCommand{} } ->
            Pid ! {visible, self()},
            io:format(" Clicked Button ~n"),
            loop(Pid);
        %% Dialogからのメッセージがあった時
        {reply, ok}->
            loop(Pid)
    end.

setVisible2.erl:

-module(setVisible2).
-export([start/0]).
%%-export([new/2]). %% API
-include_lib("wx.hrl").

start()->
    Wx = wx:new(),
    Dialog = wx:batch(fun()->new(Wx, 100) end),
    loop(Dialog).

new(Parent,Id)->
    Option = [ { size, {210, 100} } ],
    Head = "Target Display",
    Dialog = wxDialog:new(Parent, Id, Head, Option),

    Str = "Push close Button.",
    OPST1 = [{pos, {50,10}}],
    wxStaticText:new( Dialog, 1 , Str, OPST1),
 
    wxDialog:connect(Dialog, close_window),

    Dialog.

%% 閉じるボタン押下時の動作
loop(Dialog)->
    receive
        %% closeボタン押下時
        #wx{event=#wxClose{ type = close_window }}->
            wxDialog:show(Dialog, [{show, false}]),
            loop(Dialog);
        %% 他ウィンドウのボタンが押下された時
        {visible, _From} ->
            %% Dialogを表示する
            wxDialog:show(Dialog, [{show, true}]),
            _From ! {reply, ok},
            loop(Dialog)
    end.





2011年10月15日土曜日

Erlang 固定サイズのFrameのサイズを表示する

そのFrame画面内に、wxStaticTextでFrameの幅と高さを表示させるサンプル。

表示画面:


ソース:


-module(getSize).
-export([start/0]).
-include_lib("wx.hrl").

start()->
    Wx = wx:new(),
    Frame = wx:batch(fun()->create_window(Wx) end),
    wxWindow:show(Frame),
    loop(),
    %wx:destory(),
    ok.

create_window(Wx)->

    Option = [ { size, {310, 100 } } ],

    Frame = wxFrame:new(Wx,
                         ?wxID_ANY,
                        "show Size of Display!",
                       Option),

    %% get size
    [ { size, {X ,Y } } ] = Option,
    Width = string:concat("width = ", integer_to_list(X)),
    Height = string:concat("height = ", integer_to_list(Y)),

    %% create text
    OPST1 = [{pos, {110,10}}],
    OPST2 = [{pos, {110,30}}],
    wxStaticText:new( Frame, 1 , Width, OPST1),
    wxStaticText:new( Frame, 2 , Height, OPST2),

    wxFrame:connect( Frame, close_window ),

    Frame.

loop()->
    receive
        #wx{ obj = Obj, event = #wxClose{ type = close_window } } ->
            io:format("~p Closing window ~n",[self()]),
            wxWindow:destroy(Obj),
            ok
    end.

2011年9月11日日曜日

Erlang time() ローカル時刻 Sample サンプル string to_upperもね


Rubyのプログラミングの勉強をしている。
そこで参考書内のサンプルを打ち込んでいるが、それをErlangに置き換えてみている。
time関数とstring:to_upper関数を使っていた。サンプルとして載せる。

Erlangでコンパイルすると、warningが発生するが問題なし。
(上にあるif文において、1つ目のガードが必ずfalseになるという警告と、2つ目が必ずtrueなので、3つ目のガードが評価されないという警告が発生する。)

-module('Sample028').
-export([start/0]).

start() ->
    if
6 rem 4 == 0 ->
   S =  "six is a multiple of four.";
6 rem 2 == 0 ->
   S = "six is odd.";
true ->
   S = "six is even."
    end,
    io:format("a0:~p~n",[S]),

    {Hour,_,_} = time(),
 
    if
Hour >= 12 -> T = "good afternoon";
true -> T = "good morning"
    end,
    T1 = string:to_upper(T),
    io:format("a1:~p~n",[T1]).

2011年8月28日日曜日

Erlang re replace 正規表現 Sample サンプル 1つ以上を置換

前回だか、正規表現を使って文字列を置換しようとして、初めにパターンマッチしたものしか置換できなくて困っていた。
だが、パターンマッチしてヒットしたものすべてを置換することに成功。そのサンプルを。
しかし、もっと良いやり方があるのではと思う。reモジュールをもっと勉強しないと。だが、直近で正規表現は必要ない。正規表現はまた別の機会に。

ソース:

-module(re_replace_multi).
-export([start/0,binList_to_list/1]).

%%--------------------------------------------------------------------
%% @doc
%% @spec start() -> list() | error
%% @end
%%--------------------------------------------------------------------
start() ->
    Regexp = ["Erlang"],
    %% compile the Regular Expression
    case re:compile (Regexp) of
{ok,MP} ->
   Subject = ["My favorite Language is Erlang. Erlang. Erlang."],
   do_regexp (MP,Subject);
{error, ErrSpec} ->
   io:format ("Compile Error ~p~n",[ErrSpec]),
   error
    end.
 
%%--------------------------------------------------------------------
%% @doc
%% @spec do_regexp(MP) -> list() | error
%% @type MP = mp()
%% @end
%%--------------------------------------------------------------------
do_regexp (MP,Subject) ->
 
    io:format("subject:~p~n",[Subject]),

    case re:run(Subject, MP) of
{match, Captured} ->
   io:format ("match:~p~n",[Captured]),
   Rep = "Ruby",
   io:format("Replace to ~p from \"Erlang\".~n",[Rep]),
   Replace = re:replace(Subject, MP, [Rep]),
   %Tmp = [binary_to_list(X) || X <- Replace],
   %Replace1 = lists:append(Tmp),
   Sub = binList_to_list (Replace),
   do_regexp(MP,[Sub]);
nomatch ->
   io:format ("nomatch~n"),
   Subject
    end.
%%--------------------------------------------------------------------
%% @doc
%% @spec binList_to_list (list() | binary()) -> list()
%% @end
%%--------------------------------------------------------------------
binList_to_list ([]) ->
    [];
binList_to_list (Lists)
  when is_binary(Lists)
-> binary_to_list(Lists);
binList_to_list (Lists)
  when is_list(Lists)
-> [Head|Tails] = Lists,
  case is_binary(Head) of
      true ->
  HeadStr = binary_to_list(Head),
  HeadStr ++ binList_to_list(Tails);
      false ->
  Head ++ binList_to_list(Tails)
  end.

実行結果:
1> c(re_replace_multi).
{ok,re_replace_multi}
2> re_replace_multi:start().
subject:["My favorite Language is Erlang. Erlang. Erlang."]
match:[{24,6}]
Replace to "Ruby" from "Erlang".
subject:["My favorite Language is Ruby. Erlang. Erlang."]
match:[{30,6}]
Replace to "Ruby" from "Erlang".
subject:["My favorite Language is Ruby. Ruby. Erlang."]
match:[{36,6}]
Replace to "Ruby" from "Erlang".
subject:["My favorite Language is Ruby. Ruby. Ruby."]
nomatch
["My favorite Language is Ruby. Ruby. Ruby."]
3> 

Erlang re replace マッチした文字を置換する Sample サンプル

パターンマッチした文字を置換しようとしていたときのサンプル。
最初にマッチしたものしかできなかった。
エレガントじゃないので、あまり載せたくないけど。

ソース:

-module(re_replace).
-export([start/0,binList_to_list/1]).

%%--------------------------------------------------------------------
%% @doc
%% @spec start() -> list() | error
%% @end
%%--------------------------------------------------------------------
start() ->
    Regexp = ["Erlang"],
    %% compile the Regular Expression
    case re:compile (Regexp) of
{ok,MP} ->
   do_regexp (MP);
{error, ErrSpec} ->
   io:format ("Compile Error ~p~n",[ErrSpec]),
   error
    end.
   
%%--------------------------------------------------------------------
%% @doc
%% @spec do_regexp(MP) -> list() | error
%% @type MP = mp()
%% @end
%%--------------------------------------------------------------------
do_regexp (MP) ->
    Subject = ["My favorite Language is Erlang. Erlang. Erlang."],
    io:format("subject:~p~n",[Subject]),

    case re:run(Subject, MP) of
{match, Captured} ->
   io:format ("match:~p~n",[Captured]),
   Rep = "Ruby",
   io:format("Replace to ~p from \"Erlang\".~n",[Rep]),
   Replace = re:replace(Subject, MP, [Rep]),
   %Tmp = [binary_to_list(X) || X <- Replace],
   %Replace1 = lists:append(Tmp),
   binList_to_list (Replace);
nomatch ->
   io:format ("nomatch~n"),
   error
    end.
%%--------------------------------------------------------------------
%% @doc
%% @spec binList_to_list (list() | binary()) -> list()
%% @end
%%--------------------------------------------------------------------
binList_to_list ([]) ->
    [];
binList_to_list (Lists)
  when is_binary(Lists)
-> binary_to_list(Lists);
binList_to_list (Lists)
  when is_list(Lists)
-> [Head|Tails] = Lists,
  case is_binary(Head) of
      true ->
  HeadStr = binary_to_list(Head),
  HeadStr ++ binList_to_list(Tails);
      false ->
  Head ++ binList_to_list(Tails)
  end.

出力結果:
4> re_replace:start().
subject:["My favorite Language is Erlang. Erlang. Erlang."]
match:[{24,6}]
Replace to "Ruby" from "Erlang".
"My favorite Language is Ruby. Erlang. Erlang."
5> 

今ひらめいた。パターンマッチした文字を全て置換する方法。
今度載せようと思う。

Erlang re compile エラー サンプル Sample

Erlangのreモジュールのcompileメソッドでエラーを出してみた。

ソース:

-module(re_compile_exception).
-export([start/0]).

%%--------------------------------------------------------------------
%% @doc
%% @spec start() ->
%% @end
%%--------------------------------------------------------------------
start () ->
    do_exception().

%%--------------------------------------------------------------------
%% @doc
%% @spec do_exception() -> ok | error.
%% @end
%%--------------------------------------------------------------------
do_exception () ->
    Regexp = "*Erlang",
    case re:compile(Regexp) of
{ok, MP} ->
   io:format("Success to compile MP:~p~n", [MP]),
   ok;
{error, ErrSpec} ->
   io:format("ErrSpec:~p~n", [ErrSpec]),
   error
end.

出力結果:
3> re_compile_exception:start().
ErrSpec:{"nothing to repeat",0}
error
4>