Haskell分部 [英] Division in Haskell

查看:132
本文介绍了Haskell分部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Haskell中创建一个函数,只将列表中的evens减半,并且遇到问题。当我运行编译器时,它抱怨说你不能执行一个int的除法,并且我需要一个小数的int类型声明。我试图将类型声明更改为float,但这只是产生了另一个错误。

  halfEvens :: [Int]  - >>我已经在下面包含了函数的代码,并且希望有任何形式的帮助。 [Int] 
halfEvens [] = []
halfEvens(x:xs)|奇数x = halfEvens xs
|否则= x / 2:halfEvens xs

感谢您的阅读。

解决方案

使用 div ,它执行整数除法:

  halfEvens :: [Int]  - > [Int] 
halfEvens [] = []
halfEvens(x:xs)|奇数x = halfEvens xs
|否则= x`div` 2:halfEvens xs

(/) 函数需要类型为Fractional的参数,并执行标准划分。 div 函数需要类型为Integral类型的参数,并执行整数除法。 更准确地说, code> div 和 mod 向负无穷转。他们的表兄弟 quot rem ,其行为与 div 和 mod 在模块化运算时通常是正确的(例如,在计算给定日期的星期几时),而 quot rem 稍微快一点(我认为)。



 >在GHCi中玩一下:

:t div
div :: Integral a => a - > a - > a
> :t(/)
(/)::小数a => a - > a - > a
> 3/5
0.6
> 3`div` 5
0
> (-3)`div` 5
-1
> (-3)``5
0
> [x`mod` 3 | x < - [ - 10..10]]
[2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0 ,1,2,0,1]
> [x`rem` 3 | x < - [ - 10..10]]
[-1,0,-2,-1,0,-2,-1,0,-2,-1,0,1,2, 0,1,2,0,1,2,0,1]


I'm making a function in Haskell that halves only the evens in a list and I am experiencing a problem. When I run the complier it complains that you can't perform division of an int and that I need a fractional int type declaration. I have tried changing the type declaration to float, but that just generated another error. I have included the function's code below and was hoping for any form of help.

halfEvens :: [Int] -> [Int]
halfEvens [] = []
halfEvens (x:xs) | odd x = halfEvens xs
                 | otherwise = x/2:halfEvens xs

Thank you for reading.

解决方案

Use div, which performs integer division:

halfEvens :: [Int] -> [Int]
halfEvens [] = []
halfEvens (x:xs) | odd x = halfEvens xs
                 | otherwise = x `div` 2 : halfEvens xs

The (/) function requires arguments whose type is in the class Fractional, and performs standard division. The div function requires arguments whose type is in the class Integral, and performs integer division.

More precisely, div and mod round toward negative infinity. Their cousins, quot and rem, behave like integer division in C and round toward zero. div and mod are usually correct when doing modular arithmetic (e.g. when calculating the day of the week given a date), while quot and rem are slightly faster (I think).

Playing around a bit in GHCi:

> :t div
div :: Integral a => a -> a -> a
> :t (/)
(/) :: Fractional a => a -> a -> a
> 3 / 5
0.6
> 3 `div` 5
0
> (-3) `div` 5
-1
> (-3) `quot` 5
0
> [x `mod` 3 | x <- [-10..10]]
[2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,0,1]
> [x `rem` 3 | x <- [-10..10]]
[-1,0,-2,-1,0,-2,-1,0,-2,-1,0,1,2,0,1,2,0,1,2,0,1]

这篇关于Haskell分部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆