2013-02-13 39 views
0

嘿傢伙,所以我想要獲取一個單詞列表並返回一個列表就像它,但 與每次他們顯示爲連續單詞時作出以下替換。認識哈斯克爾類型的問題

一個例子是you,並把它變成u

我給出如下:

hep :: [Word] -> [Word] 
type Word = String 

什麼現在是給我的問題是,我試圖使用CASE表達式,這樣我會不會有重複的代碼,但我得到以下錯誤

Couldn't match expected type `Char' with actual type `[Char]' 
In the pattern: "You" 
In a case alternative: "You" -> "u" : hep xs 
In the expression: case a of { "You" -> "u" : hep xs } 

從下面的代碼

hep [] = [] 
hep [a:xs] = case a of 
    "You" -> "u":hep xs 

有人告訴我是什麼問題嗎?

編輯:

我加入以下代碼

hep [] = [[]] 
hep (a:xs) = case a of 
    "you" -> "u":hep xs 
    "are" -> "r":hep xs 
    "your" -> "ur":hep xs 
    "boyfriend" -> "bf":hep xs 
    "girlfriend" -> "gf":hep xs 
    "great" -> "gr8":hep xs 
    a -> a:hep xs 

現在我將如何能夠增加的情況下,這樣如果列表中包含在訂單2個或3的某些話,我可以把它變成一個首字母縮略詞?

防爆

["By","The","way"] = ["btw"] 
+0

這給了我與「你」完全相同的錯誤 - >'你' – 2013-02-13 03:28:03

+0

適合我。我得到一個額外的「」在返回列表的末尾,不知道這是否意圖 – 2013-02-13 04:10:24

+0

奇怪,現在它適用於我哈哈。 我該怎麼去添加2個以上的案例,以便我可以比較三個單詞並縮寫? 例如:「By」,「The」,「way」會變成「btw」 – 2013-02-13 04:14:02

回答

3

你試圖去匹配字符串列表清單,但hep類型是[Word] -> [Word],這違背這一點。錯誤信息是指這個事實。

但我猜你實際上想要的是這個?

hep [] = [] 
hep (a:xs) = case a of 
    "You" -> "u":hep xs 
    a -> a:hep xs 
+0

謝謝,這幫助我很多。沒有注意到支架丟失。 順便說一句,當我添加額外的情況下,我得到一個錯誤。 Imma編輯線程,以便更清楚地閱讀它。 – 2013-02-13 03:42:10

0

是這樣的嗎?

"By" -> let (y:ys) = xs 
     in if y=="The" && head ys=="Way" 
       then "btw": hep (drop 2 xs) 
       else a:hep xs 

雖然我不想連續寫50次。這個怎麼樣?

import Data.List 
import Data.Maybe 

hep [] = [] 
hep (a:xs) = case a of 
       "you" -> "u":hep xs 
       "are" -> "r":hep xs 
       "your" -> "ur":hep xs 
       "boyfriend" -> "bf":hep xs 
       "girlfriend" -> "gf":hep xs 
       "great" -> "gr8":hep xs 
       "by" -> matchPhrase 3 
       "see" -> matchPhrase 2 
       a -> a:hep xs 
      where matchPhrase num = 
        let found = lookup (concat $ take num (a:xs)) phrase_list 
        in case found of 
         Just _ -> fromJust found : hep (drop num (a:xs)) 
         Nothing -> a:hep xs 

phrase_list = [("bytheway", "btw"), ("seeyou","cu")]