-1

一直在解决一些haskell问题,被困在这两个问题上,答案很简单,但我的大脑无法解决。

编写一个函数,确定它的三个参数中有多少相等(即它返回 0、2 或 3)。

howManyEqual :: Int -> Int -> Int -> Int
howManyEqual x y z
    | x == y && x == z && y == z = 3
    | 

编写一个函数,返回它的三个整数参数中有多少大于它们的平均值。

howManyAboveAverage :: Int -> Int -> Int -> Int
howManyAboveAverage x y z
    | x > average(x y z) && y > average(x y z) && z > average(x y z) = 3
    where
    average a b c = ((a + b + c) / 3)

有人可以帮我完成这些吗:)

谢谢

4

2 回答 2

2

Edited as first solution was a bit of an overkill :)

First solution just uses plain guards:

howManyEqual :: Int -> Int -> Int -> Int
howManyEqual x y z
  | x == y && y == z = 3
  | x /= y && x /= z && y /= z = 0
  | otherwise = 2

Second solution uses some basic functions such as filter and length.

howManyAboveAverage :: Int -> Int -> Int -> Int
howManyAboveAverage x y z = length . filter (>average) $ [x,y,z]
  where average = (x + y + z) `div` 3

I don't think the integer division div is going to be a problem in this case. it truncates the decimal, but seeing as the inputs are integers anyways: x > avg implies x > floor(avg) and x <= avg implies x <= floor(avg)

Hope that works! Let me know if you have any questions.

于 2013-11-02T18:20:53.177 回答
1

你最好开始在列表中思考,在第一个任务中maximum

import Data.List (group,sort)

是你的朋友吗

howManyEqual x y z = "length of longest group of equal things" - 1

howManyAboveAverage x y z = let xs = [x,y,z]
                                avg = undefined -- you can do that
                            in length $ "get all elements > average from" xs

在第二部分中,一个名为的函数filter很有帮助。

我知道这不是有效的 haskell 代码,但它应该可以帮助您解决该问题。

编辑:

那么你必须在第一种情况下多写一点,在第二种情况下 - 过滤器在标准库中

howManyEqual :: Int -> Int -> Int -> Int
howManyEqual x y z
    | x == y && x == z = 3 
    | x == y && x /= z = 2
    | x    z && y    z = 2
    | x    y && y    z = 2
    | otherwise = 0
于 2013-11-02T16:54:08.067 回答