首页 > 解决方案 > 哈斯克尔。返回一个数字列表,其中至少存在一个与“n”相同的数字

问题描述

给定一个数字列表“ lst”和数字“ n”。返回一个数字列表,其中至少存在一个与 " n" 中相同的数字。数字系统被认为是十进制的。

该函数应返回以下结果:

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

我使用“列表理解”解决了这个问题。我遍历列表中的数字,将它们转换为“元素字符串”,并为每个元素获取这些元素的“不同集合列表”,并将它们与从给定数字获得的不同集合列表进行比较。如果列表的长度为> 0,那么我将此项包含在结果列表中。我使用函数“”解决了这个问题subsequences,它返回列表中每个元素的所有可能的迭代;和函数“intersect”,它返回两个列表的公共元素列表:

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

但是该函数因错误而崩溃,请帮助我修复它。

<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 [] 

标签: haskelllist-comprehensiontype-mismatch

解决方案


谢谢罗宾·齐格蒙德!这是根据他的建议构建的功能。

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]

推荐阅读