简体   繁体   English

无法将类型`[]'与'IO'匹配 - Haskell

[英]Couldn't match type `[]' with `IO' — Haskell

I'm beginner in Haskell. 我是Haskell的初学者。 In this task i'm performing the split operation but i'm facing problem because of type mis match. 在这个任务中,我正在执行拆分操作,但由于类型错配,我面临问题。 I'm reading data from text file and the data is in table format. 我正在从文本文件中读取数据,数据采用表格格式。 Ex. 防爆。 1|2|Rahul|13.25. In this format. 以这种格式。 Here | 这里| is delimiter so i want to split the data from the delimiter | 是分隔符,所以我想从分隔符|分割数据 and want to print 2nd column and 4th column data but i'm getting the error like this 并希望打印第二列和第四列数据,但我得到这样的错误

  "Couldn't match type `[]' with `IO'
    Expected type: IO [Char]
      Actual type: [[Char]]
    In the return type of a call of `splitOn'"

Here is my code.. 这是我的代码..

module Main where

import Data.List.Split

main = do
    list <- readFile("src/table.txt")
    putStrLn list
    splitOn "|" list

Any help regarding this will appreciate.. Thanks 任何关于此的帮助将表示赞赏..谢谢

The problem is that you're trying to return a list from the main function, which has a type of IO () . 问题是您正在尝试从main函数返回一个列表,该函数具有IO ()类型。

What you probably want to do is print the result. 您可能想要做的是打印结果。

main = do
    list <- readFile("src/table.txt")
    putStrLn list
    print $ splitOn "|" list

Not Haskell, but it looks like a typical awk task. 不是Haskell,但它看起来像一个典型的awk任务。

cat src/table.txt | cat src / table.txt | awk -F'|' awk -F'|' '{print $2, $4}' '{print $ 2,$ 4}'

Back to Haskell the best I could find is : 回到Haskell我能找到的最好的是:

module Main where

import Data.List.Split(splitOn)
import Data.List (intercalate)

project :: [Int] -> [String] -> [String]
project indices l = foldl (\acc i -> acc ++ [l !! i]) [] indices

fromString :: String -> [[String]]
fromString = map (splitOn "|") . lines

toString :: [[String]] -> String
toString = unlines . map (intercalate "|")

main :: IO ()
main = do
  putStrLn =<<
    return . toString . map (project [1, 3]) . fromString =<<
    readFile("table.txt")

If not reading from a file, but from stdin, the interact function could be useful. 如果不是从文件读取,而是从stdin读取,则interact功能可能很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM