Home > Software engineering >  Question about how to return a list based on a given tuple in Haskell
Question about how to return a list based on a given tuple in Haskell

Time:10-03

This is the code I come up with, however it didn't return the correct result, could anyone give a better solution or idea?

--For example, given a tuple (2, 3) 
--could return [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)], 
--but can be in any order. 
getAll :: (Int, Int) —> [(Int,Int)] 
getAll (x,y) 
  | x == 0 && y == 0 = [(0,0)] 
  | x == 1 && y == 1 = [(1,1)] 
  | 0   1 < x && 0   1 < y 
                     = (0,0) : getAll (x 1, y 1) 

CodePudding user response:

A clean way to implement this that I can think of is by using list comprehensions:

getAll :: (Int, Int) -> [(Int,Int)]
getAll (x, y) = [(a, b) | a <- [0..x-1], b <- [0..y-1]]

If you have to solve it with recursion:

getAll :: (Int, Int) -> [(Int,Int)]
getAll (x, y) = go 0 0 where
  go x' y'
    | x' == x            = []
    | y' == y            = go (x' 1) 0
    | otherwise          = (x', y') : go x' (y' 1)

CodePudding user response:

You write

getAll (x,y) 
  | x == 0 && y == 0 = [(0,0)] 

so far so good.

  | x == 1 && y == 1 = [(1,1)] 

and this is already wrong. It should produce [(0,0), (0,1), (1,0), (1,1)].

This is clear from the description. The two Ints define two ranges,

[ (i,j) | i <- [0..x-1], j <- [0..y-1]]

This is known as List comprehensions. And in fact this code is all you need to have in your function. No need to test for any cases either. It will just work.

  • Related