运行简单的Haskell程序时解析错误 [英] Parse error while running a simple Haskell program

查看:101
本文介绍了运行简单的Haskell程序时解析错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习Haskell。我开始写一个简单的函数,它接受两个值n和x,然后显示用它计算出的两个整数值。

  test nx = do 
cell1 = round(n * n * x)
cell2 = n * n - cell1
print cell1
print cell2

但它不运行并且一直给我输入错误的解析错误。发生了什么事? 解决方案

你可能想要的是在你的 do 块中有一个 let 语句

  test nx = do 
let cell1 = round(n * n * x)
cell2 = n * n - cell1
print cell1
print cell2

这里的区别是你不能直接在 do 块,因为所有 do 块都会被调用为>>> = >> let 语句允许您定义一个本地值,就像您可以在函数定义中一样定义,如

  fx = 
let y = 2 * x
z = y * y * y
in z + z + y

函数的解析方式就像

  test nx = 
让cell1 = round(n * n * x)
cell2 = n * n - cell1
in(print cell1>> print cell2)

其中>> 只是将两个monadic动作链接在一起。请注意,这不是真的如何解除,我选择了一个在这种情况下等价的表示,但它不完全是编译器实际生成的。


I have just started learning Haskell. I'm beginning by writing a simple function that takes two values n and x, and then displays two integer values computed with it.

test n x = do
    cell1 = round(n*n*x)
    cell2 = n*n - cell1
    print cell1
    print cell2

But it doesn't run and keeps giving me a Parse error on input `=' error. What is happening?

解决方案

You've hit your first trouble with Monads. What you probably want here is a let statement inside your do block

test n x = do
    let cell1 = round (n * n * x)
        cell2 = n * n - cell1
    print cell1
    print cell2

The difference here is that you can't assign directly inside of a do block, since all do blocks desugar to calls to >>= and >>. The let statement allows you to define a local value like you can inside a function definition like

f x =
    let y = 2 * x
        z = y * y * y
    in z + z + y

The way your function would desugar would be like

test n x =
    let cell1 = round (n * n * x)
        cell2 = n * n - cell1
    in (print cell1 >> print cell2)

Where >> just chains two monadic actions together. Note that this is not really how it desugars, I chose a representation that is equivalent in this case but it is not exactly what the compiler would actually generate.

这篇关于运行简单的Haskell程序时解析错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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