在Haskell中,为什么|>运算符在此示例中是否超出范围错误?

时间:2016-06-13 07:35:26

标签: haskell scope

{-# LANGUAGE ScopedTypeVariables #-}

module Main where
  import Control.Applicative ((<$>))
  import Data.ByteString (ByteString)
  import qualified Data.ByteString as B
  import qualified Data.ByteString.Char8 as C
  import qualified Data.Vector.Unboxed as V
  import qualified Data.Vector as VB
  import qualified Data.List as L

  (|>) :: a -> (a -> b) -> b
  x |> f = f x

  main :: IO ()
  main =
    let
        parse (s :: ByteString) = s |> L.unfoldr (C.readInt . C.dropWhile (== ' '))
        solve (l :: Int) (ars :: VB.Vector ByteString) =
          let
              (n :: V.Vector (Int, Int)) = V.fromList [(x,y) | x <- [0..l-1], y <- [x+1..l-1]]
          in
              n
    in do
        [n,l :: Int] <- parse <$> B.getLine
        (ars :: VB.Vector ByteString) <- VB.replicateM n B.getLine
        ars 
        |> solve l 
        |> print

编译器抱怨l由于某种原因不在范围内。那是为什么?

Not in scope: `l'

此外代码看起来是因为我刚刚弄清楚ScopedTypeVariables扩展的作用。它应该是正确的语言,并在初学者教程中。过去几周它会给我带来很多痛苦。

1 个答案:

答案 0 :(得分:1)

你的缩进是错误的。以下任何一项工作。

{-# LANGUAGE ScopedTypeVariables #-}
import Data.ByteString as B
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector as VB
import Data.List as L
import Data.ByteString.Char8 as C

(|>) :: a -> (a -> b) -> b
x |> f = f x

main :: IO ()
main =
  let
    parse (s :: ByteString) = s |> L.unfoldr (C.readInt . C.dropWhile (== ' '))
    solve (l :: Int) (ars :: VB.Vector ByteString) =
      let
        (n :: V.Vector (Int, Int)) = V.fromList [(x,y) | x <- [0..l-1], y <- [x+1..l-1]]
      in
        n
  in do
    [n,l :: Int] <- parse <$> B.getLine
    (ars :: VB.Vector ByteString) <- VB.replicateM n B.getLine
    ars |> solve l |> print

-

{-# LANGUAGE ScopedTypeVariables #-}
import Data.ByteString as B
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector as VB
import Data.List as L
import Data.ByteString.Char8 as C

(|>) :: a -> (a -> b) -> b
x |> f = f x

main :: IO ()
main =
  let
    parse (s :: ByteString) = s |> L.unfoldr (C.readInt . C.dropWhile (== ' '))
    solve (l :: Int) (ars :: VB.Vector ByteString) =
      let
        (n :: V.Vector (Int, Int)) = V.fromList [(x,y) | x <- [0..l-1], y <- [x+1..l-1]]
      in
        n
  in do
    [n,l :: Int] <- parse <$> B.getLine
    (ars :: VB.Vector ByteString) <- VB.replicateM n B.getLine
    ars |>
      solve l |>
      print