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

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

    Sorry, you can't1. There are fundamental differences between tuples and lists:

    • A tuple always have a finite amount of elements, that is known at compile time. Tuples with different amounts of elements are actually different types.
    • List an have as many elements as they want. The amount of elements in a list doesn't need to be known at compile time.
    • A tuple can have elements of arbitrary types. Since the way you can use tuples always ensures that there is no type mismatch, this is safe.
    • On the other hand, all elements of a list have to have the same type. Haskell is a statically-typed language; that basically means that all types are known at compile time.

    Because of these reasons, you can't. If it's not known, how many elements will fit into the tuple, you can't give it a type.

    I guess that the input you get from your user is actually a string like "(1,2,3)". Try to make this directly a list, whithout making it a tuple before. You can use pattern matching for this, but here is a slightly sneaky approach. I just remove the opening and closing paranthesis from the string and replace them with brackets -- and voila it becomes a list.

    tuplishToList :: String -> [Int]
    tuplishToList str = read ('[' : tail (init str) ++ "]")
    

    Edit

    Sorry, I did not see your latest comment. What you try to do is not that difficult. I use these simple functions for my task:

    • words str splits str into a list of words that where separated by whitespace before. The output is a list of Strings. Caution: This only works if the string inside your tuple contains no whitespace. Implementing a better solution is left as an excercise to the reader.

    • map f lst applies f to each element of lst

    • read is a magic function that makes a a data type from a String. It only works if you know before, what the output is supposed to be. If you really want to understand how that works, consider implementing read for your specific usecase.

    And here you go:

    tuplish2List :: String -> [(String,Int)]
    tuplish2List str = map read (words str)
    

    1 As some others may point out, it may be possible using templates and other hacks, but I don't consider that a real solution.

提交回复
热议问题