开发者

Haskell simple compilation bug

开发者 https://www.devze.com 2022-12-22 12:49 出处:网络
I\'m trying to run this code: let coins = [50, 25, 10, 5, 2,1] let candidate = 11 calculate :: [Int] calculate = [ calculate (x+candidate) | x <- coins, x > candidate]

I'm trying to run this code:

let coins = [50, 25, 10, 5, 2,1]

let candidate = 11

calculate :: [Int]
calculate = [ calculate (x+candidate) | x <- coins, x > candidate]

I've read some tutorials, and it worked out ok. I'm trying to solve some small problems to give-me a feel of the language. But I'm stuck at this.

test.hs:3:0: parse error (possibly incorrect indentation)

Can anyone tell me why? I've started with haskell today so please go easy on the explanations.

I've tried to run it like:

runghc test.hs
ghc test.hs

but with:

ghci < test.hs

it gives this one:

<int开发者_如何学编程eractive>:1:10: parse error on input `='

Thanks


1) Top level declarations don't need 'let'. You probably want:

coins = [50, 25, 10, 5, 2,1]

candidate = 11

2) Calculate is explicitly typed as a list and used as a function.

Here is where you say calculate is a list of integers:

calculate :: [Int]

And inside the list comprehension you used calculate (x+candidate), but you already explicitly made calculate a list and not a function - so this can not work.

calculate = [ calculate (x+candidate) | x <- coins, x > candidate]

Perhaps you wanted something like:

newCoins = [ x + candidate | x <- coins, x > candidate]

It would help if you explained more of what you want as a result.


I'm also pretty new to haskell, but this is what I have gathered so far

In ghci, you cannot define a function without let

In a .hs file, you cannot define a function with let


Using let is tricky. In a Haskell .hs file that you intend to compile with ghc or to run with runghc or runhaskell, you don't need to use let to define values and functions. So you should just do:

test = ...
candidate = ...
calculate = ...

In a do block, or when using the interpreter which actually runs your code as though it were written inside a do block, whenever you define values and functions, you should use the let keyword. So inside a do block or within a ghci session, you might do

let test = ...
let candidate = ...
let calculate = ...

As one final note, you might use the keyword let outside of a do block or ghci session when making a temporary value to be used within a larger definition, such as:

calculate =
    let test = ... in
    let candidate = ... in
    ... {stuff that uses test and candidate}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号