简体   繁体   中英

How can I make this list deconstruction work well in haskell?

I have got 2 exercise, but I do not understand how can I make them work. I tried to figure it out but I don't understand. Can I get some help?

  1. Specify the function that produces an ordered pair from a list. The first element of the pair is the first element of the list and the second element of the pair is part of the tail of the list be. We can assume that the list is not empty.
headTail :: [a] -> (a, [a])
headTail (l: ls) = (headTail l, [ls])
  1. Give the function that gets two lists and produces an ordered pair, the first element of which is the first element of the first list, the second element of which is the second list first element! We can assume that none of the lists are empty.
doubleHead :: [a] -> [b] -> (a, b)
doubleHead (l:ls) = 

I would use pattern matching in both cases.

(l:ls) assigns the first element of the list to l and the rest to ls . You can return them as a tuple as instructed.

headTail :: [a] -> (a, [a])
headTail (l:ls) = (l, ls)

Here we only care about the first elements of both lists. So, we pattern match them into x , and y and don't capture the rest at all (indicated by _ ). And return them as a tuple.

doubleHead :: [a] -> [b] -> (a, b)
doubleHead (x:_) (y:_) = (x, y)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM