簡體   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