2017-12-24 28 views
0

map関数を理解しているかどうかを確認するための練習として、A〜Zの範囲のすべての項目にchar 'a'を追加したいと考えました。私は出力としてundestandいけないこれらの例外を取得するためリスト内のすべての項目にcharを追加するにはどうすればよいですか?

まあappearently私はいけない:

Prelude> map (++ 'A')['A'..'Z'] 

<interactive>:46:9: 
    Couldn't match expected type ‘[a]’ with actual type ‘Char’ 
    Relevant bindings include it :: [[a]] (bound at <interactive>:46:1) 
    In the second argument of ‘(++)’, namely ‘'A'’ 
    In the first argument of ‘map’, namely ‘(++ 'A')’ 
    In the expression: map (++ 'A') ['A' .. 'Z'] 

<interactive>:46:14: 
    Couldn't match expected type ‘[a]’ with actual type ‘Char’ 
    Relevant bindings include it :: [[a]] (bound at <interactive>:46:1) 
    In the expression: 'A' 
    In the second argument of ‘map’, namely ‘['A' .. 'Z']’ 
    In the expression: map (++ 'A') ['A' .. 'Z'] 

<interactive>:46:19: 
    Couldn't match expected type ‘[a]’ with actual type ‘Char’ 
    Relevant bindings include it :: [[a]] (bound at <interactive>:46:1) 
    In the expression: 'Z' 
    In the second argument of ‘map’, namely ‘['A' .. 'Z']’ 
    In the expression: map (++ 'A') ['A' .. 'Z'] 
Prelude> 

私は++が文字列が含まれるリストの連結演算子であることを理解します。

私のコードで何が間違っていますか?

+3

。多分あなたは文字列を使うことを意図していました。二重引用符を使用してください。 –

答えて

8

++は、リストの連結演算子です。リストを取得し、最後に別のリストを追加します(例:[1, 2, 3] ++ [4, 5, 6] == [1,2,3,4,5,6])。あなたの場合の問題は、キャラクターにキャラクターを追加しようとしていることです。リストにリストを追加するのではありません。

文字列は、文字のリストなので、代わりに私たちは何ができる:

map (\x -> [x] ++ ['A']) ['A'..'Z']

しかし、これは少し面倒と醜いです。リストの先頭に1つの項目を追加するだけの場合は、:演算子を使用できます。このようにして、問題を逆転させることができます。各文字の最後に 'A'を追加する代わりに、文字を 'A'の先頭に追加することができます。

例えば:

map (\x -> x : "A") ['A'..'Z']

私たちは、その後、ETAにこれを減らすことができます:あなたが気づくことのよう

map (: "A") ['A'..'Z']

、私は "A" と 'A' を交換しました。 "A"は文字のリストです。文字のリストは1つの要素になります。今度は、両方のリストを最初に変換する代わりに、入力にリストに1文字を追加できます。

そして、我々が見ることができるが、それが期待どおりに動作:あなたは文字を追加することはできません

Prelude> map (: "A") ['A'..'Z'] 
["AA","BA","CA","DA","EA","FA","GA","HA","IA","JA","KA","LA","MA","NA","OA","PA","QA","RA","SA","TA","UA","VA","WA","XA","YA","ZA"] 
関連する問題