在函数Haskell中定义变量 [英] Defining variables inside a function Haskell
问题描述
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屋!