Yaroslav
Yaroslav

Reputation: 39

Haskell. Return a list of numbers in which at least one of the same digits is present as in "n"

Given a list of numbers "lst" and the number "n". Return a list of numbers in which at least one of the same digits is present as in "n". The number system is considered decimal.

The function should return the following results:

sameDigits [1,11,45,23] 12 -> [1,11,23]
sameDigits [72,47,55] 7 -> [72, 47]

I solve the problem using "list comprehension". I iterate over the numbers from the list, convert them to a "string of elements" and get for each element a "list of different sets" of these elements, and compare them with a list of different sets obtained from a given number. If the length of the list is > 0, then I include this item in the list of results. I solve the problem using the function "subsequences", which returns all possible iterations of each element of the list; and the functions "intersect", which returns list of common elements for two lists:

 let sameDigits lst n = [ x | x <- lst, if length (tail 
        (subsequences (show x)
          `intersect` subsequences (show n))) > 0 
     then x else [] ]

But the function crashes with an error, help me fix it.

<interactive>:63:131: 
Couldn't match expected type ‘Bool’ 
         with actual type ‘[t0]’ 
In the expression: [] 
In the expression: 
    if length (tail (subsequences (show x) 
         `intersect` subsequences (show n))) > 0 
      then x else [] 
 In a stmt of a list comprehension: 
    if length (tail (subsequences (show x) 
         `intersect` subsequences (show n))) > 0 
      then x else [] 

Upvotes: 0

Views: 328

Answers (1)

Yaroslav
Yaroslav

Reputation: 39

Thanks Robin Zigmond! Here is a function built on his recommendation.

let sameDigits lst n = [ x | x <- lst, length (tail (subsequences (show x) `intersect` subsequences (show n))) > 0 ]

sameDigits [1,11,45,23] 12
-> [1,11,23]
sameDigits [72,47,55] 7
-> [72,47]

Upvotes: 1

Related Questions