如何使用where子句中的块分配行中的变量? [英] How to use variable from do block assignment line in a where clause?

查看:94
本文介绍了如何使用where子句中的块分配行中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码示例:

{-# LANGUAGE ScopedTypeVariables #-}

main = do
  putStrLn "Please input a number a: "
  a :: Int  <- readLn
  print a

  putStrLn "Please input a number b: "
  b :: Int  <- readLn
  print b

  putStrLn ("a+b+b^2:" ++ (show $ a+b+c))
    where c = b^2

由于某些原因,我不能在where子句中使用变量b,我得到的错误如下:

For some reason I cannot use variable b in a where clause, the error I get is the following:

Main3.hs:13:15: error: Variable not in scope: b
   |
13 |     where c = b^2
   |               ^

有什么想法可以在where子句中提供b吗?

Any ideas how to make b available in the where clause?

推荐答案

使用let代替where:

{-# LANGUAGE ScopedTypeVariables #-}

main = do
  putStrLn "Please input a number a: "
  a :: Int  <- readLn
  print a

  putStrLn "Please input a number b: "
  b :: Int  <- readLn
  print b

  let c = b^2
  putStrLn ("a+b+b^2:" ++ (show $ a+b+c))

该问题的原因是where子句中的变量在所有main的范围内,但是bb :: Int <- readLn之后才在范围内.通常,where子句不能引用绑定在do块内部的变量(或=右侧的任何位置,例如:f x = y*2 where y = x+1可以,但f = \x -> y*2 where y = x+1则不能)

The reason for the problem is that variables in the where clause are in scope for all of main, but b isn't in scope until after b :: Int <- readLn. In general, where clauses can't reference variables bound inside of a do block (or anywhere to the right of the =, for that matter: e.g., f x = y*2 where y = x+1 is fine but f = \x -> y*2 where y = x+1 is not).

这篇关于如何使用where子句中的块分配行中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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