【问题标题】:Haskell ProgrammingHaskell 编程
【发布时间】:2017-04-29 14:46:34
【问题描述】:

我需要实现一个函数,它接受Dists 的列表并返回Dists 的列表。我需要该函数仅返回带有标签"pass"Dists,但不知何故这不起作用。有什么帮助吗?

data Ex = Ex Float Float String String deriving Show 
data NewSt = NewSt Float Float String deriving Show 
data Dist = Dist Float NewSt Ex deriving Show 

helper1 [] = []
helper1 (Dist x (NewSt midterm1 quiz1 name1) (Ex midterm quiz name label) : xs) = if (label == "pass")
  then Dist x (NewSt midterm1 quiz1 name1) (Ex midterm quiz name label) : (helper1 xs) 
  else helper1 xs

【问题讨论】:

    标签: list haskell types


    【解决方案1】:

    使用更多的模式匹配比使用if 表达式更容易编写。

    helper1 :: [Dist] -> [Dist]
    helper1 [] = []
    helper1 (Dist x newst (Ex midterm quiz name "pass") : xs) = Dist x newst (Ex midterm quiz name "pass") : (helper1 xs)
    helper (_:xs) = helper1 xs
    

    但是,一旦您认识到您的递归已经由 filter 函数实现,就更简单了。

    helper1 :: [Dist] -> [Dist]
    helper1 = filter passed
              where passed (Dist _ _ (Ex _ _ _ "pass")) = True
                    passed _ = False
    

    【讨论】:

      【解决方案2】:

      我猜你可以这样做;

      data Ex    = Ex Float Float String String deriving Show 
      data NewSt = NewSt Float Float String deriving Show 
      data Dist  = Dist Float NewSt Ex deriving Show 
      
      myData :: [Dist]
      myData = [Dist 1 (NewSt 66 100 "John") (Ex 55 90 "John" "pass"),
                Dist 2 (NewSt 20 45 "Tom") (Ex 33 50 "Tom" "fail"),
                Dist 3 (NewSt 75 75 "Mary") (Ex 90 100 "Mary" "pass")]
      
      helper1 [] = []
      helper1 d@(Dist _ _ (Ex _ _ _ label):ds) | label == "pass" = (head d):(helper1 ds)
                                               | otherwise       = helper1 ds
      

      【讨论】:

        猜你喜欢
        • 2017-07-16
        • 2012-01-28
        • 2014-11-25
        • 2017-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-04
        • 1970-01-01
        相关资源
        最近更新 更多