我编写了一个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