我正在嘗試撰寫一個從字串中洗掉特定元素的程式,但我使用的大部分內容(如filter)僅適用于[Char]. 我真的只是不想輸入"['h','e','l','l','o']"而不是"hello". 我意識到從技術上講 aString只是一種幻想[Char],但我如何將它變為標準[Char]。另外,如果您有另一種方式來撰寫普通單詞而不是陣列格式,請告訴我。
uj5u.com熱心網友回復:
正如已經說過,String只是一個代名詞了[Char]
type String = [Char]
所以兩者可以互換使用。
尤其是,"hello" :: [Char]完全一樣"hello" :: String,都是更優雅的寫法['h','e','l','l','o']。
也就是說,您會發現并非所有在其他語言中都是“字串”的東西都String在 Haskell 中。看,串列實作實際上在特別是記憶體方面效率很低——對于 ASCII 字串,大多數語言每個字符采用 8 位或 16 位,但在 Haskell 的String型別中,每個字符都是 64 位Char加上對下一個字符的參考,總共 128 位!
這就是為什么大多數現代 Haskell 庫都避免使用String,除了像檔案名這樣的簡短內容。(順便說一句,
type FilePath = String
所以這也是可以互換的。)
這些庫用于一般字串的通常是Text,這確實是一種不同的型別,更多地對應于其他語言的實作(它在引擎蓋下使用 UTF-16)。
如果要過濾該型別的值,可以將其轉換為 listy- Stringwith unpack,也可以簡單地使用filter文本庫提供的專用版本。
在標準 Haskell 中,Text值不能定義為字串或串列文字,您需要像pack ['h','e','l','l','o']. 不過,他們可以仍然使用簡單的字串字面定義,只要你打開{-# LANGUAGE OverloadedStrings #-}:
ghci> :m Data.Text
ghci> "hello" :: Text
<interactive>:5:1: error:
? Couldn't match expected type ‘Text’ with actual type ‘[Char]’
? In the expression: "hello" :: Text
In an equation for ‘it’: it = "hello" :: Text
ghci> :set -XOverloadedStrings
ghci> "hello" :: Text
"hello"
使用另一個擴展,這也適用于串列語法:
ghci> ['h','e'] :: Text
<interactive>:9:1: error:
? Couldn't match expected type ‘Text’ with actual type ‘[Char]’
? In the expression: ['h', 'e'] :: Text
In an equation for ‘it’: it = ['h', 'e'] :: Text
ghci> :set -XOverloadedLists
ghci> ['h','e'] :: Text
"he"
uj5u.com熱心網友回復:
在 Haskell 中,方括號表示一個串列,就像在 Python 中一樣。Haskell 還使用空格語法。
您可以通過在 ghci REPL 中使用 :t 來判斷字串在 Haskell 中的型別。
:t "String" -- "String" :: [Char]
所以雙引號中的字串實際上是一個字串列。
字串串列怎么樣?
:t ["airplane","boat","car"] -- ["airplane","boat","car"] :: [[Char]]
所以字串串列是字串列的串列。
至于過濾,如果我將過濾器應用于字串,它的行為與字串列上的過濾器完全相同:
:m Data.Char
filter isUpper "String" -- returns "S"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/404601.html
標籤:
上一篇:在OCaml中派生實作
