Haskell数据类型转换问题 [英] Haskell datatype conversion problems

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

问题描述

我目前正在学习Haskell,并一直在编写一些非常简单的程序来练习.这些程序之一就是我下面的程序:

I am currently learning Haskell and have been writing a couple of very simple programs to practice as I go along. One of these programs is the one I have bellow:

import System.IO

main = do
    putStrLn "Give me year: "
    y <- getLine
    let res = show . calcPop $ read y
    putStrLn ("Population in " ++ y ++ " will be " ++ res)



pop :: Float
pop = 307357870.0
secInYear :: Float
secInYear = 365.0 * 24.0 * 60.0 * 60.0
bRate :: Float
bRate = secInYear / 7.0
dRate :: Float
dRate = secInYear / 13.0
iRate :: Float
iRate = secInYear / 35.0

calcPop :: Float -> Float
calcPop year = let years = year - 2010 in (years*bRate + years*iRate + pop - years*dRate)

它要做的是在2010年之后的一年内计算该年的估计人口,现在它可以正常工作,除了您可能已经注意到的每个数字都被转换为浮点数之外,其他所有方法都可以正常工作.现在这样做很荒谬,因为除了整数以外,没有理由让当前人口,一年中的秒数或年份本身除整数之外,不幸的是,尽管当我那样做时,我正在获取编译器错误,其中/函数表示小数整数,而 * 函数表示将浮点数作为第一个参数.现在我已经了解到,Haskell像其他语言一样,在遇到涉及int和float的操作时,只会将int更改为类似于float的行为,而此处并没有发生这种情况.有人可以解释为什么我会遇到这些错误,以及如何使int和float相互协作,因为显然我仍然对Haskell类型系统还没有足够的了解来自己解决这个问题?

What it does is take a year after 2010 and calculate the estimated population in that year, and as it is right now it works fine and all except that as you may have noticed EVERY single number is cast as a float. Now it is pretty ridiculous to do this since there is no reason to have the current population, the number of seconds in a year or the year itself for that matter as anything but ints, unfortunately though when I had it that way I was getting compiler error with the / function saying something about fractional int and with the * function saying it inferred a float as the first parameter. Now I had understood that Haskell like other languages when encountering operations involving ints and floats would just change the int to act like a float which aperantly didn't happen here. Could someone explain why I was getting these errors and how I can get ints and floats to cooperate since evidently I still don't have a good enough grasp of the Haskell type system to do it myself?

推荐答案

Haskell类型严格;它从不自动为您转换类型,除了整数文字会自动包装在 fromIntegral 中.相反,当您只需要处理 Int / Integer 时,您可能想使用更多类型适合的操作,例如`div` fromIntegral 可以在需要时升级为 Float Double .

Haskell types are strict; it never automatically converts a type for you, except that integer literals are automatically wrapped in fromIntegral. Instead, you may want to use more type-appropriate operations such as `div` when you only need to deal with Int/Integer, and fromIntegral to promote to Float or Double when needed.

(语法说明:`function` 将前缀函数转换为中缀运算符.)

(Syntax note: `function` converts a prefix function into an infix operator.)

这篇关于Haskell数据类型转换问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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