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

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

    There's a lot of things you could possibly mean. For example, if you want a few copies of a single value, you can use replicate, defined in the Prelude:

    replicate :: Int -> a -> [a]
    replicate 0 x = []
    replicate n | n < 0     = undefined
                | otherwise = x : replicate (n-1) x
    

    In ghci:

    Prelude> replicate 4 ("Haskell", 2)
    [("Haskell",2),("Haskell",2),("Haskell",2),("Haskell",2)]
    

    Alternately, perhaps you actually want to do some IO to determine the list. Then a simple loop will do:

    getListFromUser = do
        putStrLn "keep going?"
        s <- getLine
        case s of
            'y':_ -> do
                putStrLn "enter a value"
                v <- readLn
                vs <- getListFromUser
                return (v:vs)
            _ -> return []
    

    In ghci:

    *Main> getListFromUser :: IO [(String, Int)]
    keep going?
    y
    enter a value
    ("Haskell",2)
    keep going?
    y
    enter a value
    ("Prolog",4)
    keep going?
    n
    [("Haskell",2),("Prolog",4)]
    

    Of course, this is a particularly crappy user interface -- I'm sure you can come up with a dozen ways to improve it! But the pattern, at least, should shine through: you can use values like [] and functions like : to construct lists. There are many, many other higher-level functions for constructing and manipulating lists, as well.

    P.S. There's nothing particularly special about lists of tuples (as compared to lists of other things); the above functions display that by never mentioning them. =)

提交回复
热议问题