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

后端 未结 5 1509
挽巷
挽巷 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:28

    I'm guessing that, since this is for a class, and you've been studying Haskell for < 1 week, you don't actually need to do any input/output. That's a bit more advanced than you probably are, yet. So:

    • As others have said, map fst will take a list of tuples, of arbitrary length, and return the first elements. You say you know how to do that. Fine.

    • But how do the tuples get into the list in the first place? Well, if you have a list of tuples and want to add another, (:) does the trick. Like so:

      oldList = [("first", 1), ("second", 2)]
      newList = ("third", 2) : oldList
      

      You can do that as many times as you like. And if you don't have a list of tuples yet, your list is [].

    Does that do everything that you need? If not, what specifically is it missing?

    Edit: With the corrected type:

    Eq a => [(a, b)]

    That's not the type of a function. It's the type of a list of tuples. Just have the user type yourFunctionName followed by [ ("String1", val1), ("String2", val2), ... ("LastString", lastVal)] at the prompt.

提交回复
热议问题