2016-05-23 27 views
0

在Haskell學習遞歸函數的新手,想知道如何創建遞歸函數toUpper和toLower,它們接收一個Chars列表並返回相同的Chars列表,但大小寫?我嘗試使用chr和ord函數來解決它,但ord的簽名是Char - > Int,而不是[Char] - > [Int],因此它與toUpper和toLower不匹配。有任何想法嗎?如何在Haskell中更改「ord」函數的簽名?

+2

根據你的描述我會建議'映射toUpper'或者'map toLower' - 但我不確定我的問題是否正確 – Carsten

+3

*你是怎麼嘗試和使用這些?如果使用得當,它們聽起來像是你所需要的。 –

+0

'map toUpper「hello world」'給你''HELLO WORLD「' - 這是你在說什麼嗎? – Carsten

回答

-3

沒關係,現在就明白了。如果有人需要它:

toUpper::[Char] -> [Char] 
toUpper [] = [] 
toUpper (x:xs) = chr(ord(x)-32):toUpper(xs) 

toLower::[Char] -> [Char] 
toLower [] = [] 
toLower (x:xs) = chr(ord(x)+32):toLower(xs) 
+3

怎麼樣'toUpper「FOO」'或'toLower「foo」'?拋開這個問題,你只是重新實現了已經提供的「map」邏輯。 'map f [] = []'和'map f(x:xs)=(f x):(地圖f xs)'。 – chepner

+1

這是一個很糟糕的做法。 – augustss

3

這正是map功能的作用:它需要a -> b類型(任何類型ab)函數返回一個新的功能[a] -> [b]

> :t ord 
ord :: Char -> Int 
> :t map ord 
map ord :: [Char] -> [Int] 

這可以讓你的整個字符串轉換爲它的Unicode代碼點:

> map ord "foo" 
[102,111,111] 

或回

> map chr [102,111,111] 
"foo" 

爲了實現你的方法,你那麼就需要定義一個適當的功能toLowertoUpper使用

> map chr (map toLower (map ord "MyStRiNg")) 
mystring 
> map chr (map toUpper (map ord "MyStRiNg")) 
MYSTRING 

(請注意,模塊Data.Char已經提供toLower, toUpper :: Char -> Char;你可以用它們來檢查你自己的實現。)