I'm following along with this:
And I am trying to get a column of data from a CSV by variable name in the headers, earlier part given here.
Here's my code:
import Text.CSV
import Data.List
import Data.Maybe
dat <- parseCSVFromFile "/home/user/data.csv"
headers = head dat
records = tail dat
indexField :: [[Field]] -> Int -> [Field]
indexField records index = map (\x -> x !! index) records
which works:
Prelude> indexField records 0
[1,2,3]
And headers are as follows:
Prelude> headers
["id", "category", "value"]
I have the following to index by field name rather than index
indexFieldbyName :: [[Field]] -> String -> [Field]
indexFieldbyName records indexName = indexField records (fromJust (elemIndex indexName headers))
Which also works:
Prelude> indexFieldbyName records "id"
[1,2,3]
However, I want this to fail more informatively when the key is not found in headers
:
Prelude> indexFieldbyName records "meow"
Maybe.fromJust: Nothing
Here are my attempts:
indexFieldbyName2 :: [[Field]] -> String -> Either String [Field]
indexFieldbyName2 records indexName = indexField records index
where index = case (elemIndex indexName headers) of
Just v -> Right (v)
Nothing -> Left ("Index not found")
Parse error (line 31, column 5): parse error on input ‘Just’
And
indexFieldbyName3 :: [[Field]] -> String -> Either String [Field]
indexFieldbyName3 records indexName = indexField records index
where index = case v of
Just (elemIndex indexName headers) -> Right (v)
Nothing -> Left ("Index not found")
Parse error (line 44, column 4): parse error on input ‘Just’
indexFieldbyName4 :: [[Field]] -> String -> Either String [Field]
indexFieldbyName4 records indexName = indexField records index
where index = case v of
Just v -> Right (elemIndex indexName headers)
Nothing -> Left ("Index not found")
Parse error (line 37, column 4): parse error on input ‘Just’
The above were indentation issues, the just
had to be to the right of the case
. Now I have:
indexFieldbyName2' :: [[Field]] -> String -> Either String [Field]
indexFieldbyName2' records indexName = indexField records index
where index = case (elemIndex indexName headers) of
Just v -> Right (v)
Nothing -> Left ("Index not found")
<interactive>:4:39: error:
• Couldn't match expected type ‘Either String [Field]’ with actual type ‘[Field]’
• In the expression: indexField records index
In an equation for ‘indexFieldbyName2’:
indexFieldbyName2 records indexName
= indexField records index
where
index
= case (elemIndex indexName headers) of
Just v -> Right (v)
Nothing -> Left ("Index not found")
<interactive>:4:58: error:
• Couldn't match expected type ‘Int’ with actual type ‘Either String Int’
• In the second argument of ‘indexField’, namely ‘index’
In the expression: indexField records index
In an equation for ‘indexFieldbyName2’:
indexFieldbyName2 records indexName
= indexField records index
where
index
= case (elemIndex indexName headers) of
Just v -> Right (v)
Nothing -> Left ("Index not found")