[英]Error while passing strings in functions in Haskell
因此,我在haskell中嘗試了以下代碼,嘗試檢測用戶是否在字符串中輸入了“ no”或“ no”。 我也嘗試用字符串替換[[Char]],但是它會給出編譯錯誤。
wantGifts :: [[Char]] -> [[Char]]
wantGifts st = [if (x == "No" || x== "no") then "No gifts given" else "But why" | x <- st, x == head st]
上面的代碼可以編譯,但是當我將字符串傳遞給它時,它返回一條錯誤消息:
*Main> wantGifts "no I dont"
<interactive>:8:11:
Couldn't match type ‘Char’ with ‘[Char]’
Expected type: [[Char]]
Actual type: [Char]
In the first argument of ‘wantGifts’, namely ‘"no I dont"’
In the expression: wantGifts "no I dont"
In an equation for ‘it’: it = wantGifts "no I dont"
仔細查看wantGifts
的類型,它需要一個Chars List列表。 但是"no I dont"
是String
類型的,只是[Char]
。 在當前的結構中,您必須使用:
wantGifts ["no I dont"]
有幾種方法可以改善此問題,最好是使用Text
。
import Data.Text (Text)
import qualified Data.Text as T
wantGifts :: Text -> Text
wantGifts txt = if (T.isInfixOf "no" . T.toLower) txt then "No gifts given" else "But why"
您已將wantGifts
定義為采用字符串列表。 [[Char]]
等效於[String]
。 在REPL中,您將傳遞單個字符串。
如果您改為這樣做,它將編譯:
wantGifts ["no I dont"]
但是,我有一種預感,這不是您想要的。
如果您要檢測字符串中是否存在"no"
一詞,則可以使用words
function:
containsNo :: String -> Bool
containsNo = any (\w -> w == "no" || w == "No") . words
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.