1

我目前正在尝试通过学习 Haskell 数据分析来学习 Haskell (虽然之前我读过一些其他的东西,比如 Learn You a Haskell...)。有一个列表可以解析和修改 csv 数据,它不像本书建议的那样工作,即。它通过一个错误。不幸的是,我还不够好,无法更正列表。我以某种方式得到什么不起作用,但不知道正确的版本会是什么样子。我也没有真正找到使用该either函数来查看是否可以从中派生正确版本的富有表现力的示例

module LearningDataAnalysis02 where

import Data.List
import Data.Either
import Text.CSV

-- compute the average of List values
average' :: Fractional a => [a] -> 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 does not exist in this csv file."
    Just x  -> Right (fromIntegral x)
  where
    lookupResponse = findIndex (== columnName) (head csv)

applyToColumnInCSV :: ([String] -> b) -> CSV -> String -> Either String b
applyToColumnInCSV func csv column = either
    Left
    Right . func . elements columnIndex
  where
    columnIndex = getColumnInCSV csv column
    nfieldsInFile = length $ head csv
    records = tail $ filter (\record -> nfieldsInFile == length record) csv
    elements ci = map (\record -> genericIndex record ci) records

将其加载到 ghci 时收到的错误消息是:

LearningDataAnalysis02.hs:22:38:
    Couldn't match expected type ‘Either String b’
                with actual type ‘a0 -> Either a1 b0’
    Relevant bindings include
      func :: [String] -> b (bound at LearningDataAnalysis02.hs:22:20)
      applyToColumnInCSV :: ([String] -> b)
                            -> CSV -> String -> Either String b
        (bound at LearningDataAnalysis02.hs:22:1)
    In the expression: either Left Right . func . elements columnIndex
    In an equation for ‘applyToColumnInCSV’:
        applyToColumnInCSV func csv column
          = either Left Right . func . elements columnIndex
          where
              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]’
                with actual type ‘[Field]’
    Possible cause: ‘elements’ is applied to too many arguments
    In the second argument of ‘(.)’, namely ‘elements columnIndex’
    In the second argument of ‘(.)’, namely
      ‘func . elements columnIndex’
Failed, modules loaded: none.

有没有人这么好心,可以向我解释我必须如何修改清单以使其正常工作,以及为什么它不像书中建议的那样工作?

4

0 回答 0