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

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

问题描述

我有以下代码示例:

{-# 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
   |               ^

任何想法如何使 bwhere 子句中可用?

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 的范围内,但 b 不在作用域直到 b :: Int <- readLn 之后.通常,where 子句不能引用绑定在 do 块内的变量(或 = 右侧的任何地方,就此而言:例如,fx = 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子句中使用do块赋值行中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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