I’m attempting the Write Yourself a Scheme in 48 Hours tutorial and as someone new to haskell it’s pretty difficult.
I’m currently working on a problem where I’m supposed to add the ability to parse scheme vectors (section 3.4 exercise 2).
I’m using this data type:
data LispVal = Atom String
| List [LispVal]
| Vector (Array Int LispVal)
To parse, I’m looking for ‘#(‘ then trying to parse the vector contents, drop them in a list and convert that list to an array.
I’m trying to use a list parsing function that I already have and am using but it parses scheme lists into the LispVal List above and I’m having a hard time getting that back into a regular list. Or at least that’s what I think my problem is.
lispValtoList :: LispVal -> [LispVal]
lispValtoList (List [a]) = [a]
parseVector :: Parser LispVal
parseVector = do string "#("
vecArray <- parseVectorInternals
char ')'
return $ Vector vecArray
parseVectorInternals :: Parser (Array Int LispVal)
parseVectorInternals = listToArray . lispValtoList . parseList
listToArray :: [a] -> Array Int a
listToArray xs = listArray (0,l-1) xs
where l = length xs
and here’s the list parser:
parseList :: Parser LispVal
parseList = liftM List $ sepBy parseExpr spaces
Any ideas on how to fix this?
Thanks,
Simon
-edit-
Here’s the compilation error I get:
Couldn’t match expected type
a ->Parser LispVal’ In the second argument of
LispVal'
against inferred type
(.)' namelyparseList’ In the second
argument of(.)' namelylispValToList . parseList’ In the
expression: listToArray .
lispValToList . parseList
You do not provide
lispValtoListbut I suppose that it have the following typeThis would suggest the compiler to think that
parseListis of typea -> LispVal. But it is not since it isParser LispValand so something likeP String -> [(LispVal,String)].You have to extract the
LispValvalue that was parsed before putting it in a list.So
parseVectorInternalsmust probably look likeYou could write something more compact, but this code tries to be self-documented 😉