Haskell多功能,它接受两个数字并返回产品而不使用乘法(*)或除法(/)符号(Haskell multi function that takes two numbers and returns t

编程入门 行业动态 更新时间:2024-10-22 07:20:11
Haskell多功能,它接受两个数字并返回产品而不使用乘法(*)或除法(/)符号(Haskell multi function that takes two numbers and returns the product without using multiplication (*) or division (/) signs)

得到了我的Haskell类的第一个任务,它在课程的第一周似乎有点过于复杂。

问题如下:写一个Haskell函数,它接受两个自然数并返回它们的乘积。 该函数不得使用乘法(*)或除法(/)运算符。

我能想到的唯一方法就是:

product :: [Integer] -> Integer product [] = 1 product (x:xs) = x * product xs

除了有*标志。

我错过了什么,还是我只是个白痴?

Got our first assignment for my Haskell class and it seems a bit too complex for the first week of class.

The question is as follows: Write a Haskell function that takes two natural numbers and returns their product. the function must not use the multiplication (*) or division (/) operators.

The only way I can think of doing it is with this:

product :: [Integer] -> Integer product [] = 1 product (x:xs) = x * product xs

Except there is a * sign in it.

Am I missing something or am i just an idiot?

最满意答案

product :: [Integer] -> Integer product [] = 1 product (x:xs) = x * product xs

这将是一个烂摊子。 您的函数接受整数的LIST并返回一个整数。 它远不是你的规格。 现在为了乘法,它是一个操作数第二个操作数的加法时间,所以你的老师要求你使用这个基本原理来乘以2个数。

这是它的代码

product :: Integer->Integer->Integer product x 1 = x product x y = x + product x (y-1)

注意这只会乘以2个正整数。 您现在可以编辑给定的函数以合并负值。

product :: [Integer] -> Integer product [] = 1 product (x:xs) = x * product xs

This will be a mess. Your function accepts a LIST of integers and returns an integer. It is nowhere near your specifications. Now for multiplication, it is addition of one operand 2nd operand times, so your teacher has asked you to to use this basic principle to multiply 2 numbers.

Here is the code for it

product :: Integer->Integer->Integer product x 1 = x product x y = x + product x (y-1)

Beware this will only multiply 2 positive integers. You can now edit the given function to incorporate negative values too.

更多推荐

本文发布于:2023-08-07 00:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1457890.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:除法   而不   乘法   多功能   符号

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!