error handling - How does the either function work and is used appropriately in Haskell? -
i trying learn haskell learning haskell data analysis @ moment (i read other things learn haskell... before though). there listing parse , modify csv data not work way book proposes, ie. throughs error. unfortunately, not enough able correct listing. somehow not work don't know how correct version like. did not realy found expressive examples use either
function see if can derive correct version it
module learningdataanalysis02 import data.list import data.either import text.csv -- compute average of list values average' :: fractional => [a] -> average' xs = sum xs / genericlength xs readcolumn :: [string] -> [double] readcolumn xs = map read xs getcolumnincsv :: csv -> string -> either string integer getcolumnincsv csv columnname = case lookupresponse of nothing -> left "the column not exist in csv file." x -> right (fromintegral x) lookupresponse = findindex (== columnname) (head csv) applytocolumnincsv :: ([string] -> b) -> csv -> string -> either string b applytocolumnincsv func csv column = either left right . func . elements columnindex columnindex = getcolumnincsv csv column nfieldsinfile = length $ head csv records = tail $ filter (\record -> nfieldsinfile == length record) csv elements ci = map (\record -> genericindex record ci) records
the error message when loading ghci is:
learningdataanalysis02.hs:22:38: couldn't match expected type ‘either string b’ actual type ‘a0 -> either a1 b0’ relevant bindings include func :: [string] -> b (bound @ learningdataanalysis02.hs:22:20) applytocolumnincsv :: ([string] -> b) -> csv -> string -> either string b (bound @ learningdataanalysis02.hs:22:1) in expression: either left right . func . elements columnindex in equation ‘applytocolumnincsv’: applytocolumnincsv func csv column = either left right . func . elements columnindex columnindex = getcolumnincsv csv column nfieldsinfile = length $ head csv records = tail $ filter (\ record -> nfieldsinfile == length record) csv elements ci = map (\ record -> genericindex record ci) records learningdataanalysis02.hs:24:20: couldn't match expected type ‘a0 -> [string]’ actual type ‘[field]’ possible cause: ‘elements’ applied many arguments in second argument of ‘(.)’, namely ‘elements columnindex’ in second argument of ‘(.)’, namely ‘func . elements columnindex’ failed, modules loaded: none.
is kind , can explain me how have modify listing make work , why not work way book suggest it?
Comments
Post a Comment