I wrote a Haskell program and got a compile error I don't understand.
The program should:
- Get the command line arguments
- Concatenate tokenized arguments back to a single
String
- Read the
String
into aNestedList
data type - Flatten the
NestedList
into aList
- Print the
List
Unfortunately, it won't compile because of a type ambiguity.
Haskell Code:
{-
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
Compile Error:
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
Could someone help me understand how/why there is a type ambiguity and how I can make the code unambiguous.