让我们开始吧
boom :: Int -> Maybe a -> Maybe a
boom 0 x = x
boom n x = boom (n-1) (x >>= (\y -> Just y))
Run Code Online (Sandbox Code Playgroud)
这是一个简单的函数,它只是将>>=一个Maybe值反复推入一个简单的\y -> Just y函数中.
现在,该计划
main = do
let z = boom 10 (Nothing :: Maybe Int)
putStrLn $ show z
Run Code Online (Sandbox Code Playgroud)
一瞬间跑得很快.但是,该计划
main = do
let z = boom 10000000 (Nothing :: Maybe Int)
putStrLn $ show z
Run Code Online (Sandbox Code Playgroud)
即使我编译ghc -O(GHC 7.8.3),也需要几秒钟才能完成.
这意味着Haskell无法优化此功能.Nothing即使没有必要,它也会被反复推入一个函数中.
我的问题是, …
对于代码
class Boomable a where
boom :: a
instance Boomable Int where
boom = 100
instance Boomable Double where
boom = 1.2
Run Code Online (Sandbox Code Playgroud)
为什么
boom + 1
Run Code Online (Sandbox Code Playgroud)
给我2.2?
为什么它使用Double版本而不是像我预期的那样给出歧义错误?
我希望不得不做::Int或做::Double其中任何一个boom或1为此工作.
a = 2+2.0从.hsGHCi中的文件加载并进行:t a演出a :: Double.
另一方面,做let b = 2+2.0和:t bGHCi表明b :: Fractional a => a.
你怎么能从这两个文件中推断出这个?
我发现这个官方文档几乎不可理解.
我把它放在Shapes.hs中:
module Shapes
( Shape(Rectangle)
) where
data Shape = Circle | Rectangle deriving (Show)
Run Code Online (Sandbox Code Playgroud)
然后我进入GHCi并加载它:l Shapes.
打字Circle工作.我只Rectangle在paranthesis中指定,为什么它有效?
我把它放进去~/Desktop/Shapes.hs:
module Shapes
( Shape(Rectangle)
) where
data Shape = Circle | Rectangle deriving (Show)
Run Code Online (Sandbox Code Playgroud)
然后我这样做:
cd ~/Desktop
ghci
ghci> :m +Shapes
<no location info>:
Could not find module `Shapes'
It is not a module in the current program, or in any known package.
ghci> import Shapes
<no location info>:
Could not find module `Shapes'
It is not a module in the current program, or in any known package.
Run Code Online (Sandbox Code Playgroud)
为什么我会收到此错误?
我也试过先编译ghc -c Shapes.hs.它仍然无法正常工作.
我在我的OS X 10.9.2 …
1 有类型 Num a => a
1.0 有类型 Fractional a => a
为什么1+1.0有类型Fractional a => a
这对我来说似乎很奇怪,因为1它不是分数.只是1.0分数.那么怎么1变成分数并结合1.0形成一个小数?
因为只有Num拥有+运营商,如果它似乎更自然的我1.0变成了Num,得到了与组合1以产生最终的Num(虽然这将是奇怪的一点,因为我们会失去信息,从去1.0到1).
haskell ×6