繁体   English   中英

Haskell - 如何将元组列表写入文本文件

[英]Haskell - How do I write a tuple list to a text file

我从 .txt 获取文本,对其进行处理。 我从文本中得到元音和它们的数量。 我无法将元组列表 [(Char, Int)] 写入文本文件。 我想让每一行都有一个字母和它的编号,但我根本不会写。

`

import Data.List
import Char

add :: Eq a => a -> [(a, Int)] -> [(a, Int)]
add x [] = [(x, 1)]
add x ((y, n):rest) = if x == y
    then (y, n+1) : rest
    else (y, n) : add x rest
 
count :: Eq a => [a] -> [(a, Int)]
count = sortBy f . foldr add [] where
    f (_, x) (_, y) = compare y x

ff x = filter (\x->elem (fst x) "aeyioAEYIO") x

fff x = ff (count x)

main :: IO ()
main = do
   src <- readFile "input.txt"
   writeFile "output.txt" (operate src)

operate :: [(Char, Int)] -> String
operate = fff

它给出了一个错误:

*** Term           : operate
*** Type           : [Char] -> [(Char,Int)]
*** Does not match : [(Char,Int)] -> String

操作类型错误,因为 fff 的类型为[Char] -> [(Char, Int)]

operate :: [(Char, Int)] -> String
operate = fff

类型推断建议[Char] -> [(Char, Int)]

很好,但是返回类型仍然需要是[(String, Int)]如果我们想把这个函数的输出提供给formatOne

formatOne :: Show a => (String, a) -> String
formatOne (s, i) = s ++ " : " ++ show i

operate :: String -> [(String, Int)]
operate =  map (\(x,y) -> (x:"", y)) . fff
-- (\(x,y) -> (x:"", y)) this lambda turns first element of tuple from Char to String

-- unlines joins elements of list into string while separating elements with \n
formatAll = unlines . map formatOne

main :: IO ()
main = do
  src <- readFile "input.txt"
  writeFile "output.txt" (formatAll (operate src))

暂无
暂无

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

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