haskell - 哈斯克尔。返回一个数字列表,其中至少存在一个与“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 []
解决方案
谢谢罗宾·齐格蒙德!这是根据他的建议构建的功能。
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]
推荐阅读
- android - 从 JNI 中的 jibjectArray 访问值时出现问题
- oauth-2.0 - Airflow Google OAuth 登录重定向到 127.0.0.1:8080 而不是域名
- reactjs - 刚吃了我的第一个 create-app-react npm start 和 localhost , 127.0.0.1 不工作
- java - 使用 Java 在 h2 中的 MySQL TIME() 函数
- ios - 使用凝固汽油弹的 commit:_config 时出现问题,找不到配置文件
- count - PowerBI 对会议数量进行分类
- android - 如何使用 AssetFileDescriptor 的偏移量、长度和文件路径从 NDK 读取文件?
- python - 有没有办法列出用于 Python 中特定项目的所有依赖项
- javascript - React - Mobx - Fetch - DRY 最佳实践
- c# - 如何从 .netcore 中的 wsdl 中删除方法名称