Numeration count inside a recursive function

后端 未结 3 1345
无人共我
无人共我 2021-01-23 18:50

I want do do something like:

>enumerate [\"banana\", \"potato\", \"ice\"]
[(1, \"banana\"), (2, \"potato\"), (3, \"ice\")]

I wrote:

<
相关标签:
3条回答
  • 2021-01-23 18:57

    There is already a function which does this called zip (zip :: [a] -> [b] -> [(a,b)]). Now for your function you just can pass a list with 1,2,... as first argument and get your result, e.g.

    enumerate :: [String] -> [(Int, String)]
    enumerate = zip [1..]
    

    EDIT:

    If you also want to implement your own zip function, just use:

    zip' :: [a] -> [b] -> [(a,b)]
    zip' _ [] = []
    zip' [] _ = []
    zip' (x:xs) (y:ys) = (x,y):zip' xs ys
    

    You take two lists ([a] and [b]) and put each element into a tuple. Edge cases are of cores when one of the lists is empty you return an empty list. Otherwise you use pattern matching to get the first element of the list put them into a tuple and call zip' again with the tail of the list.

    0 讨论(0)
  • 2021-01-23 19:06

    Don't be afraid to write a support function, in fact, see it as opportunity: Why the arbitrary starting value 1? Why not have a function

    >enumerateFrom 42 ["banana", "potato", "ice"]
    [(42, "banana"), (43, "potato"), (44, "ice")]
    

    Once you have that, enumerate is easy.

    Edit: Either give your aux function a real name, IMHO enumerateFrom is good or move it into a where clause if you know that already. And listen to chi, use x : ... instead of [x] ++ ...

    0 讨论(0)
  • 2021-01-23 19:16

    As you clarified you wanted to implement your own zip:

    zip' [] _ = []
    zip' _ [] = []
    zip' (x:xs) (y:ys) = (x,y) : zip' xs ys
    
    0 讨论(0)
提交回复
热议问题