在函数Haskell中定义变量 [英] Defining variables inside a function Haskell

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

问题描述

我是Haskell的一个新手,我刚刚10分钟前就开始了。我想弄清楚如何在函数内部定义一个变量。假设我有函数

pre $ foo :: Int - > Int
foo a =
b = a * 2
b
- 是的,我知道,它并没有做任何有趣的事情

当我在 GHCi 中运行它时,出现语法错误!如何在一个函数内定义一个变量?

解决方案

有两种方法可以做到这一点:

  foo a = b其中b = a * 2 
foo a = let b = a * 2 in b

在大多数情况下,它们之间的选择是一种审美而不是技术性的选择。更确切地说,其中可能只附加到定义,而 let ... in ... 可能在任何地方使用表达式是允许的。 其中 let 引入了块,使得在这两种情况下都可以方便地使用多个内部变量。


I am a huge newbie to Haskell, I actually just started 10 minutes ago. I am trying to figure out how to define a variable inside a function. Lets say I have the function

foo :: Int -> Int
foo a = 
    b = a * 2
    b
-- Yes, I know, it doesn't do anything interesting

When I run it in GHCi I get a syntax error! How can you define a variable inside a function?

解决方案

There are two ways to do this:

foo a = b where b = a * 2
foo a = let b = a * 2 in b

In most cases, the choice between them is an aesthetic rather than technical one. More precisely, where may only be attached to definitions, whereas let ... in ... may be used anywhere an expression is allowed. Both where and let introduce blocks, making multiple internal variables convenient in both cases.

这篇关于在函数Haskell中定义变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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