IT練習ノート

IT関連で調べたこと(実際は嵌ったこと)を書いています。

99 questions/Solutions/31の回答の作り方(よくない例)

試行錯誤の履歴です。

もっとうまい試行錯誤の方法があるはず。。

-- 2から10までの配列を作る

Prelude> ( \x -> [2..x] ) 10
[2,3,4,5,6,7,8,9,10]

-- 作った配列に対して、なんらかの関数を適用してみる。
-- filterを使うつもりだが、まずは結果が分かりやすいようにmapで確認する。

Prelude> ( \x -> map (*2) [2..x] ) 10
[4,6,8,10,12,14,16,18,20]

-- filterを使ってみる。
-- わかりやすいようにとりあえず配列を2で割ってみる。

Prelude> ( \x -> filter (\y -> ((y/2)==0.0)) [2..x] ) 10
[]
Prelude> ( \x -> filter (\y -> ((y/2)==0)) [2..x] ) 10
[]

-- 結果が空の配列になってて、おかしいなと思い、考え直す。
-- 0比較の誤りに気づく。

Prelude> ( \x -> filter (\y -> ((y/2)==1)) [2..x] ) 10
[2.0]

-- 期待通りに1個できた。
-- 指定された10を作った2から10までの配列で割っていくように変える。

Prelude> ( \x -> filter (\y -> ((x/y)==1)) [2..x] ) 10
[10.0]

-- 期待通りに1個結果がでた。
-- 結果の数を数えることにする。

Prelude> ( \x -> length ( filter (\y -> ((x/y)==1)) [2..x] ) 10 )

<interactive>:16:9:
    Couldn't match expected type `a1 -> t0' with actual type `Int'
    The function `length' is applied to two arguments,
    but its type `[a0] -> Int' has only one
    In the expression:
      length (filter (\ y -> ((x / y) == 1)) [2 .. x]) 10
    In the expression:
      (\ x -> length (filter (\ y -> ((x / y) == 1)) [2 .. x]) 10)

-- 括弧を指定まちがえた模様

Prelude> ( \x -> length ( filter (\y -> ((x/y)==1)) [2..x] ) ) 10 
1

-- 一個でてきた。
-- 真偽値で結果が得られるようにlengthを使うように変更した。

Prelude> ( \x -> (length ( filter (\y -> ((x/y)==1)) [2..x] ) ) == 1 )10 

True

-- 素数を求めるには、割り算ではなくmodで結果がゼロを判断するので、ロジック変更。

Prelude> ( \x -> (length ( filter (\y -> (mod x y)==0)) [2..x] ) ) == 1 )10 

-- また括弧間違い??

<interactive>:23:64: parse error on input `)'

Prelude> ( \x -> length ( filter (\y -> (mod x y)==0)) [2..x] ) ) 10 

<interactive>:25:56: parse error on input `)'


Prelude> ( \x -> length ( filter (\y -> (mod x y)==0)) [2..x] ) ) 10 

<interactive>:26:56: parse error on input `)'

-- わからなくなってきたので、modそのものを確認してみる。

Prelude> mod 10 2
0

-- 真偽値にするまえに、いったんlength数の確認をしてみる。

Prelude> ( \x -> length ( filter (\y -> ((mod x y)==0)) [2..x] ) ) 10 
3

-- うまくいったので、真偽値に変えてみる。

Prelude> ( \x -> ( length ( filter (\y -> ((mod x y)==0)) [2..x] ) ) == 1 )10 
False

-- うまくいったみたいので、他の値で確認する。

Prelude> ( \x -> ( length ( filter (\y -> ((mod x y)==0)) [2..x] ) ) == 1 ) 7
True
Prelude> ( \x -> ( length ( filter (\y -> ((mod x y)==0)) [2..x] ) ) == 1 ) 13
True
Prelude> 

-- とりあえずできたが、非効率なロジックなので、どうしようか。。