得到了我的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 xsExcept 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 xsThis 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.
更多推荐
发布评论