簡體   English   中英

如何在Haskell中更改“ ord”函數的簽名?

[英]How can I change the “ord” function's signature in Haskell?

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

這正是map函數的作用:它接受a- 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 ;您可以使用它們來檢查自己的實現。)

沒關系,現在就知道了。 萬一有人需要它:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM