【问题标题】:Haskell: Parse error in pattern: accHaskell:模式中的解析错误:acc
【发布时间】:2015-03-14 02:19:10
【问题描述】:

我找到了一些 Cloud Haskell Demos 并尝试运行它,但我得到一个错误,我不知道为什么。错误看起来像:

MasterSlave.hs:18:9:pattern:acc 中的解析错误

MasterSlave.hs 中的代码是:

module MasterSlave where

import Control.Monad
import Control.Distributed.Process
import Control.Distributed.Process.Closure
import PrimeFactors

slave :: (ProcessId, Integer) -> Process ()
slave (pid, n) = send pid (numPrimeFactors n)

remotable ['slave]

-- | Wait for n integers and sum them all up
sumIntegers :: Int -> Process Integer
sumIntegers = go 0
  where
    go :: Integer -> Int -> Process Integer
    go !acc 0 = return acc
    go !acc n = do
      m <- expect
      go (acc + m) (n - 1)

data SpawnStrategy = SpawnSyncWithReconnect
                   | SpawnSyncNoReconnect
                   | SpawnAsync
  deriving (Show, Read)

master :: Integer -> SpawnStrategy -> [NodeId] -> Process Integer
master n spawnStrategy slaves = do
  us <- getSelfPid

  -- Distribute 1 .. n amongst the slave processes
  spawnLocal $ case spawnStrategy of
    SpawnSyncWithReconnect ->
      forM_ (zip [1 .. n] (cycle slaves)) $ \(m, there) -> do
        them <- spawn there ($(mkClosure 'slave) (us, m))
        reconnect them
    SpawnSyncNoReconnect ->
      forM_ (zip [1 .. n] (cycle slaves)) $ \(m, there) -> do
        _them <- spawn there ($(mkClosure 'slave) (us, m))
        return ()
    SpawnAsync ->
      forM_ (zip [1 .. n] (cycle slaves)) $ \(m, there) -> do
        spawnAsync there ($(mkClosure 'slave) (us, m))
        _ <- expectTimeout 0 :: Process (Maybe DidSpawn)
        return ()

  -- Wait for the result
  sumIntegers (fromIntegral n)

这段代码有什么问题?

【问题讨论】:

  • 您是否启用了BangPatterns
  • 另外remotable ['slave] 看起来应该是TemplateHaskell,你也打开了吗?
  • 我认为没有。如何设置此标志?
  • {-# LANGUAGE ExtensionName #-} 放在源文件的顶部(在模块声明之前),用于您要启用的每个扩展。
  • 非常感谢!这就是问题所在。

标签: haskell parse-error


【解决方案1】:

您需要启用两种语言扩展,BangPatternsTemplateHaskell。这些可以通过两种方式启用:

  1. 从命令行编译时
  2. 在源文件中使用了扩展名(首选)

要在命令行启用它们,请为您需要的每个扩展传递标志 -XExtensionName,因此对于您的情况,您将拥有 ghc -XTemplateHaskell -XBangPatterns source_file_name.hs

要在源代码中启用它们,请使用文件顶部的{-# LANGUAGE ExtensionName #-} pragma:

{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE BangPatterns #-}
module MasterSlave where

...

语言扩展是 GHC Haskell 的重要组成部分。有一些非常常见,以至于它们出现在大多数现实世界的应用程序中,例如OverloadedStrings,它允许您将TextBytestringString 文字语法一起使用,而MultiParamTypeClasses 对于许多应用程序来说是必不可少的。更高级的库,例如 lensmtl。其他常见的包括Derive* 扩展,如DeriveFunctorDeriveFoldable 等,它们让编译器可以派生更多的扩展,而不仅仅是标准的EqShowRead 等。

在您的情况下,BangPatterns 添加了用于在函数参数和数据类型字段中指定额外严格性的语法。这有助于减少隐性懒惰带来的问题,但如果你不小心,它也可能会用太重的手来使用。 TemplateHaskell 为 GHC 内置的模板/宏语言启用了许多额外的语法。库作者可以编写模板 Haskell 函数,这些函数接受数据类型、表达式、函数名称或其他结构,并构建不需要留给用户的样板代码,但在其他方面不容易或简洁抽象。 lens 库与 Yesod Web 框架一起使用了很多。

【讨论】:

    猜你喜欢
    • 2012-01-23
    • 2013-01-29
    • 1970-01-01
    • 2012-12-24
    • 2012-09-28
    • 2017-10-29
    • 2019-05-03
    • 2017-07-18
    • 2018-02-14
    相关资源
    最近更新 更多