【问题标题】:Sum the squares of the even numbers from a list in Haskell对 Haskell 列表中偶数的平方求和
【发布时间】:2014-09-30 11:50:34
【问题描述】:

我想对一个列表中偶数的平方求和。我试试这个,但显示错误。

sumaDeCuadrados :: [Int] -> Int
sumaDeCuadrados (x:xs) = sumaListAux (map f l) 0 
    where l = filter even (x:xs) 
          f = x * x
sumaDeCuadrados _ = 0

而 sumaListAux 是一个定义为 ..

的函数
sumaListAux :: [Int] -> Int -> Int
sumaListAux [] r = r
sumaListAux (x:xs) r = x + sumaListAux xs r

【问题讨论】:

  • 切勿在未发布详细信息的情况下在问题中声明“存在错误”。它与仅说明“有修复”的答案一样翔实。
  • f = x * x 替换为f x = x * x 即可。第一个方程定义一个数字,第二个方程定义一个函数。

标签: list dictionary haskell filter


【解决方案1】:

对一个列表中偶数的平方求和。

Haskell 在某些方面是一种声明性语言,因此您只需声明这些内容的含义即可。

-- declare a list
> let list = [1..10]

-- declare what the even elements of a lsit are
> let evens xs = filter even xs

-- declare what the squares of a list are
> let squares xs = map (^2) xs

总和已经存在,sum。所以现在你的句子:

 sum ​​the squares of the even numbers

可以转置为:

> sum . squares . evens $ list
220

【讨论】:

    【解决方案2】:

    实际的问题是,map 期望第一个参数是一个函数,它接受一个整数并返回一个整数,但你传递的是一个整数。这就是为什么您会收到这样的错误消息

    Couldn't match expected type `Int -> Int' with actual type `Int'
    In the first argument of `map', namely `f'
    In the first argument of `sumaListAux', namely `(map f l)'
    In the expression: sumaListAux (map f l) 0
    

    因此,您需要将f 定义为一个单独的函数,以便map 可以将该函数应用于l。我建议使用适当的名称命名该函数,例如 squarer

    squarer :: Int -> Int
    squarer x = x * x
    
    sumaDeCuadrados xs = sumaListAux (map squarer (filter even xs)) 0
    

    然后你可以这样称呼它

    main = print $ sumaDeCuadrados [1, 2, 3, 4, 5]
    -- 20
    

    【讨论】:

      【解决方案3】:

      基于上述答案,完全可以使用高阶函数来做到这一点。

      sumEvenSquares :: (Num a) => [a] -> a
      sumEvenSquares xs = sum(map(^2)(filter even xs))
      

      在这种情况下,您可以使用偶数谓词过滤列表,并将函数 (^2) 映射到它上面。从此返回的列表中,您可以对其进行求和。

      【讨论】:

        猜你喜欢
        • 2018-01-29
        • 2014-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多