简体   繁体   中英

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

I get text from.txt, process it. I get vowels and their number from the text. I cannot write tuple list [(Char, Int)] to text file. I want to make each line to have a letter and its number, but I can't write it at all.

`

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

It gives out an error:

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

operate type is wrong because fff has type [Char] -> [(Char, Int)]

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

type inferenece suggests [Char] -> [(Char, Int)] ,

good but return type still needs to be [(String, Int)] if we want to feed output of this function to 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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