【问题标题】:A function that takes a list and an Integer returns an element of the list接受一个列表和一个整数的函数返回列表的一个元素
【发布时间】:2016-06-21 08:30:57
【问题描述】:

编写一个名为findID 的函数,它接受:

  • (学生姓氏(字符串)、学生 ID(3 位整数))对的列表,
  • 学生姓名

然后返回:

  • 与此姓名匹配的学生 ID 列表。

这行得通:

findID xs m = [ snd(x) | x<-xs, fst(x) ==  m]

结果:

*Main> findID [("josh",123),("becky",456)] "josh"
[123]

但我不想使用列表推导。通过这样的方式:

findID' (x:xs) m 
    | fst(x) == m = snd(x)
    | otherwise = findID' xs

我错过了什么?

【问题讨论】:

  • filtermap ?
  • 您不需要在 Haskell 中的函数参数周围使用括号。您通常应该使用snd x 而不是snd(x)

标签: list function haskell recursion list-comprehension


【解决方案1】:

如果您想编写自己的递归解决方案,类似这样的方法会起作用

findId [] _ = []
findId ((n,i):xs) m | n==m =   i: findId xs m
                    | otherwise = findId xs m

【讨论】:

  • 谢谢您,这对您很有帮助!
【解决方案2】:

按照@Carsten 的建议使用mapfitler

import Data.String
findID :: [(String, Integer)] -> String -> [Integer]
findID xs name = map snd $ filter ((==name).fst) xs

测试:

*Main> let xs = [("Smith", 123), ("Jones", 456), ("Tran", 789), ("Smith", 012)]
*Main> findID xs "Jones"
[456]
*Main> findID xs "Smith"
[123,12]
*Main> findID xs []
[]

【讨论】:

    【解决方案3】:

    当您递归调用 findID' 时,您缺少 m 参数。

    另外请注意,您只返回第一个匹配值,而不是完整列表,因此这个新函数没有做正确的事情。

    【讨论】:

    • 空列表也没有基本情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    • 2022-01-15
    相关资源
    最近更新 更多