[英]Haskell “Couldn't match expected type ‘a’ with actual type ‘[a0]’”
[英][HASKELL]Couldn't match expected type `[a0]' with actual type `[a1] -> Bool'
我正在嘗試編寫一個從文件中逐行讀取的函數:
readMyFile = do
contents <- readFile "input.txt"
if(null sStringV == True)
then do
let sStringV = lines contents
let sString = head sStringV
let sStringV = tail sStringV
return sString
else do
let sString = head sStringV
let sStringV = tail sStringV
return sString
我將sStringV聲明為null
sStringV = null
當我編譯此代碼時,我收到以下錯誤。
Couldn't match expected type `[a0]' with actual type `[a1] -> Bool'
In the first argument of `null', namely `sStringV'
In the first argument of `(==)', namely `null sStringV'
In the expression: (null sStringV == True)
我不明白我的問題在哪里......
null
是一個函數[a] -> Bool
並返回輸入列表是否為空。 因此sStringV
類型為[a] -> Bool
。
在行if (null sStringV == True)
null
的參數應該是一個列表,而不是null
函數本身。
看來你應該將sStringV
的聲明sStringV
為類似的東西
sStringV :: String
sStringV = ""
但是,您應該知道, let sStringV = lines contents
不會為sStringV
- 它只聲明一個隱藏舊定義的新變量sStringV
。 您無法在readMyFile
函數中修改sStringV
。
看起來你正試圖像使用命令式語言一樣使用Haskell。
null()不測試變量是否為null。 null()測試列表是否為空。 關鍵詞是list ,即你必須在列表上調用null。 所以你有兩個選擇:
1)您可以在空列表上調用null():
null [] -->True
2)您可以在包含以下內容的列表上調用null():
null [1, 2, 3] --> False
還要注意寫作:
if(null sStringV == True)
是多余的。 null()將列表作為參數,如果列表為空則返回True,如果列表包含某些內容則返回False。 因此,您需要編寫的是:
if(null sStringV)
then do .... --executed if sStringV is an empty list
else do ... --excuted if sStringV is a list that contains something
這是一個例子:
dostuff:: [a] -> IO ()
dostuff alist = if null alist
then putStrLn "hello"
else putStrLn "goodbye"
ghci>:l 1.hs
[1 of 1] Compiling Main ( 1.hs, interpreted )
Ok, modules loaded: Main.
ghci>dostuff []
hello
ghci>dostuff [1, 2, 3]
goodbye
ghci>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.