[英]How to combine the letters in two strings in haskell
我正在學習Haskell並遵循http://learnyouahaskell.com/starting-out上的指南。 我正處於顯示的位置:
ghci> let nouns = ["hobo","frog","pope"]
ghci> let adjectives = ["lazy","grouchy","scheming"]
ghci> [adjective ++ " " ++ noun | adjective <- adjectives, noun <- nouns]
["lazy hobo","lazy frog","lazy pope","grouchy hobo","grouchy frog",
"grouchy pope","scheming hobo","scheming frog","scheming pope"]
我想要實現的,它是類似的,但結合兩個字符串中包含的字母,因為字符串基本上是Haskell中的char列表,這是我嘗試的:
[x ++ ' ' ++ y | x <- "ab", y <- "cd"]
但編譯器抱怨:
Prelude> [y ++ ' ' ++ y | x <- "abd", y <- "bcd"]
<interactive>:50:2:
Couldn't match expected type ‘[a]’ with actual type ‘Char’
Relevant bindings include it :: [[a]] (bound at <interactive>:50:1)
In the first argument of ‘(++)’, namely ‘y’
In the expression: y ++ ' ' ++ y
<interactive>:50:7:
Couldn't match expected type ‘[a]’ with actual type ‘Char’
Relevant bindings include it :: [[a]] (bound at <interactive>:50:1)
In the first argument of ‘(++)’, namely ‘' '’
In the second argument of ‘(++)’, namely ‘' ' ++ y’
In the expression: y ++ ' ' ++ y
<interactive>:50:14:
Couldn't match expected type ‘[a]’ with actual type ‘Char’
Relevant bindings include it :: [[a]] (bound at <interactive>:50:1)
In the second argument of ‘(++)’, namely ‘y’
In the second argument of ‘(++)’, namely ‘' ' ++ y’
我做了很多嘗試,例如將表達式包裝在括號中以獲取列表,將空間更改為String而不是char ...我怎樣才能使它工作?
謝謝
++
僅適用於列表,但x
和y
僅為Char
。 畢竟,它們是String
(= [Char]
)中的元素,而LYAH示例包含Char
列表: [String] = [[Char]]
:
-- [a] -> [a] -> [a]
-- vv vv
[y ++ ' ' ++ y | x <- "abd", y <- "bcd"]
-- ^ ^ ^
-- Char Char
-- vs
-- [String] [String]
-- vvvvvvvvvv vvvvv
[adjective ++ " " ++ noun | adjective <- adjectives, noun <- nouns]
-- ^^^^^^^ ^^^^
-- String String
相反,使用(:)
將彼此的字符合並到空列表中:
[x : ' ' : y : [] | x <- "abd", y <- "bcd"]
x ++ ' ' ++ y
這里的實際問題是,您嘗試連接三個字符,並且只為項目列表定義一個函數。 ++
實際上會連接兩個列表,而不是兩個單獨的項目並給出一個列表。
因此,您可以通過將所有字符轉換為字符串來修復程序,就像這樣
> [[x] ++ " " ++ [y] | x <- "ab", y <- "cd"] ["ac","ad","bc","bd"]
注意" "
,而不是' '
。 因為" "
表示只包含空格字符的字符串,但' '
表示只是空格字符。
或者,將y
轉換為String,使用帶有' '
cons
運算符,並將其連接到x
轉換為字符串,就像這樣
> [[x] ++ (' ' : [y]) | x <- "ab", y <- "cd"] ["ac","ad","bc","bd"]
或者, 如chi所建議的那樣 ,甚至更簡單和直觀地創建一個字符列表,就像這樣
> [[x, ' ', y] | x <- "ab", y <- "cd"] ["ac","ad","bc","bd"]
注意:用[]
包裝一個字符使其成為一個只包含一個字符的字符列表。 它基本上變成了一個String。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.