-1

我想制作一个 Haskell 模块来计算有多少汽车p和摩托车m,当我有轮子r和马车的n总数时。

我有以下功能:

p = (r - 2p) / n
m = n - ((r-2) / 2))
n = p + m
r = 4p + 2m

但是我如何将其定义为 Haskell 函数呢?是开始

calculator :: Int -> Int -> Int -> Int
calculator r n = ...

如何正确组合要定义的功能p, m, n, ?rcalculator

4

1 回答 1

3

您将在这里遇到一些问题,您在一些地方遗漏了乘法运算符(必须2 * p不是2p),并且所有变量都不是函数而是相互定义的值,您的calculator函数必须启动使用小写字母,您应该使用div而不是/整数(/未为该Int类型定义)。你可能想要这样的东西:

numCars :: Int -> Int -> Int
numCars wheels carriages = undefined {- formula for calculating number of cars -}

numBikes :: Int -> Int -> Int
numBikes wheels carriages = undefined {- formula for calculating number of motorcycles -}

calculator :: Int -> Int -> (Int, Int)
calculator wheels carriages = (numCars wheels carriages, numBikes wheels carriages)

main :: IO ()
main = do
    putStr "Enter the number of wheels:  "
    wStr <- getLine
    putStr "Enter the number of carriages:  "
    cStr <- getLine
    let (cars, bikes) = calculator (read wStr :: Int) (read cStr :: Int)
    putStr "The number of cars is:  "
    print cars
    putStr "The number of bikes is:  "
    print bikes
于 2013-11-05T14:49:36.753 回答