我編寫了一個Haskell程序,並得到了編譯錯誤,我不明白。瞭解一個Haskell類型歧義的案例
程序應該:
- 獲取命令行參數
- 拼接標記化參數回單
String
- 閱讀
String
爲NestedList
數據類型 - 拼合
NestedList
成List
- 打印
List
不幸的是,由於類型不明確,它不會編譯。
Haskell代碼:
{-
Run like this:
$ ./prog List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]]
Output: [1,2,3,4,5]
-}
import System.Environment
import Data.List
data NestedList a = Elem a | List [NestedList a]
deriving (Read)
main = do
args <- getArgs
print . flatten . read $ intercalate " " args
flatten :: NestedList a -> [a]
flatten (Elem x) = [x]
flatten (List x) = concatMap flatten x
編譯錯誤:
prog.hs:8:21:
Ambiguous type variable `a0' in the constraints:
(Read a0) arising from a use of `read' at prog.hs:8:21-24
(Show a0) arising from a use of `print' at prog.hs:8:3-7
Probable fix: add a type signature that fixes these type variable(s)
In the second argument of `(.)', namely `read'
In the second argument of `(.)', namely `flatten . read'
In the expression: print . flatten . read
有人能幫助我瞭解如何/爲什麼有型歧義和我怎樣才能使代碼明確。
您認爲GHC應該找到什麼類型? – misterbee