简体   繁体   English

在列表中查找元素并返回字符串 - haskell

[英]finding elements in a list and return strings - haskell

Hi I want to display the names of the dogs that have 0 mins walked for the their second day嗨,我想显示第二天步行 0 分钟的狗的名字

type Dogs = (String, Float, Float, [Int]) -- Dog,Age,Weight,Time walked daily


testData :: [Dogs]
testData = [("Morris", 5, 8, [0,0,5,8,8,0,0]), 
        ("Tinks", 3, 10, [12,8,15,0,0,0,2]), 
        ("Cash", 6, 11, [0,6,5,0,0,0,3]), 
        ("Lou", 5, 17, [0,2,10,7,8,2,2]),
        ("Kobi", 10, 12, [0,0,8,3,6,7,5]) 
        ("Nala", 7, 8, [8,16,20,3,4,9,2])] 

So the output would be Morris and Kobi as they have 0 second in the list but I don't know how to go about this, I'm quite new to haskell.因此,output 将是 Morris 和 Kobi,因为它们在列表中的秒数为 0,但我不知道如何 go 关于这个,我对 Z64E88B02AD08079E342D827715AB4EC 很陌生。 I understand that I should use !! 1我知道我应该使用!! 1 !! 1 to get the second element out of a list but I don't know how to do this for multiple lists within tuples within a list and then output as string for the names. !! 1从列表中获取第二个元素,但我不知道如何对列表中的元组中的多个列表执行此操作,然后将 output 作为名称的字符串。 Any help would be appreciated thanks任何帮助将不胜感激谢谢

First off, you can create a separate function for determining whether the condition you are looking for is met:首先,您可以创建一个单独的 function 来确定您正在寻找的条件是否满足:

isDay2Walked :: Dogs -> Bool
isDay2Walked (_, _, _, (_:x:_)) = x /= 0 -- pattern matching would be more elegant than (!! 1)
isDay2Walked _ = False -- return something if there is no information about the second day

Then, use this predicate in a filter over your list, and extract the first element - the name:然后,在列表的过滤器中使用此谓词,并提取第一个元素 - 名称:

getDogName :: Dogs -> String
getDogName (name, _, _, _) = name

getDogsNotWalkedOnDay2 :: [Dogs] -> [String]
getDogsNotWalkedOnDay2 = map getDogName . filter (not . isDay2Walked)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM