简体   繁体   English

在Haskell中输入声明

[英]Type declaration in Haskell

I just started learning Haskell. 我刚开始学习Haskell。 I decided to set myself a goal of implementing an old algorithm of mine http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.79.7006&rep=rep1&type=pdf 我决定为自己设定一个实现我的旧算法的目标http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.79.7006&rep=rep1&type=pdf

As a start I wrote the following code 首先,我编写了以下代码

phi [] = [1..]
phi (p:pl) = (phi pl) `minus` (map (p*) $ phi pl)
primes x
       | x < 2 = []
       | otherwise = smallprimes ++ (takeWhile (<=x) $tail $ phi $ reverse smallprimes)
     where  smallprimes = primes $ sqrt x

minus (x:xs) (y:ys) = case (compare x y) of
         LT -> x  :    minus xs (y:ys)
         EQ ->         minus xs    ys
         GT ->         minus (x:xs) ys
minus xs        _   = xs

This functions as expected, except that the list of primes comes as floating point! 这个函数按预期运行,除了素数列表是浮点数! A little thought told me that since the signature of sqrt is 有点想法告诉我,因为sqrt的签名是

sqrt :: (Floating a) => a -> a

the Haskell compiler has decided that primes is returning a list of floats. Haskell编译器已经确定primes返回一个浮点列表。 However, when I tried to tell it that 但是,当我试图告诉它时

phi :: [Integer] -> [Integer]

which is what I want, the compiler has a problem: 这就是我想要的,编译器有一个问题:

No instance for (Floating Integer)
  arising from a use of `sqrt` at ...

So how do I signify the phi takes as input a list of integers and as output produces an infinite list of Integers? 那么我如何表示phi将整数列表作为输入,并且输出会产生无限的整数列表?

The problem in your code is, that sqrt expects a floating point number and returns the same. 您的代码中的问题是, sqrt期望浮点数并返回相同的值。 You have to use a wrapper that converts the type to make it work. 您必须使用转换类型的包装器才能使其工作。 (That's essentially, what the error message says): (这基本上就是错误信息所说的):

smallprimes = primes . ceiling . sqrt . fromIntegral $ x

Haskell has no automatic conversion between different numeric types, as this is not possible with the type system Haskell has. Haskell在不同的数字类型之间没有自动转换,因为Haskell所具有的类型系统不可能。

take a look at that: Converting numbers 看一看: 转换数字

ceiling should too the trick (as FUZxxl pointed out allready) ceiling应该是伎俩(正如FUZxxl指出的那样)

IMHO the difficult part here is that the languages we are used to cast types by pointing to your target - Haskell switches the logic in a mind-bending way here ... 恕我直言,这里的困难部分是我们用来通过指向你的目标来转换类型的语言--Haskell在这里以一种令人费解的方式切换逻辑......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM