用Python和Haskell开发的计算器应用
发布时间:2023-12-09 08:49:19
Python是一种容易学习和使用的编程语言,而Haskell是一种函数式编程语言,它具有强大的表达能力和静态类型检查机制。下面是使用Python和Haskell开发的计算器应用的示例:
Python示例:
# 定义计算器类
class Calculator:
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
def multiply(self, a, b):
return a * b
def divide(self, a, b):
if b == 0:
raise ZeroDivisionError("除数不能为0")
return a / b
# 创建计算器对象
calculator = Calculator()
# 使用计算器进行计算
result = calculator.add(3, 4)
print(result) # 输出:7
result = calculator.subtract(5, 2)
print(result) # 输出:3
result = calculator.multiply(2, 3)
print(result) # 输出:6
result = calculator.divide(10, 2)
print(result) # 输出:5
Haskell示例:
-- 定义计算器函数
add :: Int -> Int -> Int
add a b = a + b
subtract :: Int -> Int -> Int
subtract a b = a - b
multiply :: Int -> Int -> Int
multiply a b = a * b
divide :: Int -> Int -> Either String Int
divide a 0 = Left "除数不能为0"
divide a b = Right (a div b)
-- 使用计算器进行计算
result = add 3 4
print result -- 输出:7
result = Main.subtract 5 2
print result -- 输出:3
result = multiply 2 3
print result -- 输出:6
result = divide 10 2
case result of
Left err -> print err -- 输出除数不能为0
Right val -> print val -- 输出:5
这两个示例代码展示了如何使用Python和Haskell开发计算器应用。你可以根据自己的需求和偏好选择其中之一进行开发。无论你选择使用哪种语言,都可以利用这些示例代码作为起点,进一步扩展和优化你的应用。
