How do I add x tuples into a list x number of times?

后端 未结 5 1508
挽巷
挽巷 2021-01-25 20:59

I have a question about tuples and lists in Haskell. I know how to add input into a tuple a specific number of times. Now I want to add tuples into a list an unknown number of t

5条回答
  •  滥情空心
    2021-01-25 21:18

    When doing functional programming, it is often better to think about composition of operations instead of individual steps. So instead of thinking about it like adding tuples one at a time to a list, we can approach it by first dividing the input into a list of strings, and then converting each string into a tuple.

    Assuming the tuples are written each on one line, we can split the input using lines, and then use read to parse each tuple. To make it work on the entire list, we use map.

    main = do input <- getContents
              let tuples = map read (lines input) :: [(String, Integer)]
              print tuples
    

    Let's try it.

    $ runghc Tuples.hs
    ("Hello", 2)
    ("Haskell", 4)
    

    Here, I press Ctrl+D to send EOF to the program, (or Ctrl+Z on Windows) and it prints the result.

    [("Hello",2),("Haskell",4)]
    

    If you want something more interactive, you will probably have to do your own recursion. See Daniel Wagner's answer for an example of that.

提交回复
热议问题