【问题标题】:How can I parse a string to a function in Haskell?如何将字符串解析为 Haskell 中的函数?
【发布时间】:2013-05-16 18:09:22
【问题描述】:

我想要一个看起来像这样的函数

readFunc :: String -> (Float -> Float)

类似这样的操作

>(readFunc "sin") (pi/2)
>1.0

>(readFunc "(+2)") 3.0
>5.0

>(readFunc "(\x -> if x > 5.0 then 5.0 else x)") 2.0
>2.0

>(readFunc "(\x -> if x > 5.0 then 5.0 else x)") 7.0
>5.0

难以置信的幼稚方法(注意这必须用{-# LANGUAGE FlexibleContexts #-}编译)

readFunc :: (Read (Float -> Float)) => String -> (Float -> Float)
readFunc s = read s

给予

No instance for (Read (Float -> Float)) ...

这是有道理的,因为不存在这样的实例。我知道我可以通过编写从StringFloat -> Float 的映射逐个字符地解析输入字符串,但我希望至少能够解析前奏曲中最常见的函数,即使这样也比我想承诺。有没有简单的方法可以做到这一点?

只有一个使用提示的解决方案

import Language.Haskell.Interpreter hiding (typeOf)
import Data.Typeable (typeOf)

data Domain = Dom Float Float Float Float Domain
            | SDom Float Float Float Float 
            deriving (Show, Read)

--gets all the points that will appear in the domain
points (SDom a b c d) m = [(x, y)|x <- [a, a+m .. b], y <- [c, c+m .. d]]
points (Dom a b c d next) m = points next m ++ [(x, y)|x <- [a, a+m .. b], y <- [c, c+m .. d]]

readFunc = do
    putStrLn "Enter a domain (as Dom x-min x-max y-min y-max subdomain, or, SDom x-min x-max y-min y-max)"
    domain' <- getLine
    let domain = (read domain') :: Domain
    --
    putStrLn "Enter a mesh size"
    meshSize' <- getLine
    let meshSize = (read meshSize') :: Float 
    --
    putStrLn "Enter an initial value function (as f(x,y))"
    func' <- getLine
    values' <- runInterpreter $ setImports["Prelude"] >>
                                eval ("map (\\(x,y) -> " ++ func' ++ ")" ++ show (points domain meshSize))
    let values = (\(Right v) -> (read v)::([Float])) values'

    --the haskell expression being evaluated
    putStrLn $ ("map (\\(x,y) -> " ++ func' ++ ")" ++ show (points domain meshSize)) 

    --prints the actual values
    putStrLn $ show values 

    --the type is indeed [float]
    putStrLn $ show $ typeOf values 

【问题讨论】:

  • 你需要它做什么?也许有更简单的方法来解决根本问题。
  • 我正在编写一个程序,它实现了几种用于求解二维微分方程的数值技术。我想要一个命令行程序,它将以匿名 Haskell 函数(当然是字符串格式)的形式从用户那里获取输入,以便定义问题的初始条件。
  • 解释表达式就够了吗?见stackoverflow.com/questions/5582926/…

标签: haskell text-parsing


【解决方案1】:

您可以使用hint 包或plugins。我将向您展示前者(部分原因是我的 Windows 安装显然有点损坏,因为 cabal 不同意我安装 C 的信念,因此 cabal 安装插件失败)。

字符串 -> 函数很简单:

import Language.Haskell.Interpreter

getF :: String -> IO (Either InterpreterError (Float -> Float))
getF xs = runInterpreter $ do
   setImports ["Prelude"]
   interpret xs (as :: Float -> Float)

您可能希望将其他模块添加到导入列表中。这测试为

ghci> getF "sin" >>= \(Right f) -> print $ f (3.1415927/2)
1.0
ghci> getF "(\\x -> if x > 5.0 then 5.0 else x)" >>= \(Right f) -> print $ f 7
5.0

(注意转义字符\的转义。)

错误信息

您可能已经注意到,结果包含在 Either 数据类型中。 Right f 是正确的输出,而 Left err 给出了 InterpreterError 消息,这很有帮助:

ghci> getF "sinhh" >>= \(Left err) -> print err
WontCompile [GhcError {errMsg = "Not in scope: `sinhh'\nPerhaps you meant `sinh' (imported from Prelude)"}]

示例玩具程序

当然,您可以在代码中使用either 来处理这个问题。让我们做一个假的例子respond。你真正的将包含你程序的所有数学。

respond :: (Float -> Float) -> IO ()
respond f = do
   -- insert cunning numerical method instead of
   let result = f 5
   print result

你的程序的一个简单的、一次性的、无用的版本可能是

main = 
   putStrLn "Enter your function please:"
   >> getLine 
   >>= getF 
   >>= either print respond 

示例会话

ghci> main
Enter your function please:
\x -> x^2 + 4
29.0
ghci> main
Enter your function please:
ln
WontCompile [GhcError {errMsg = "Not in scope: `ln'"}]

它会为你做类型检查:

ghci> main
Enter your function please:
(:"yo")
WontCompile [GhcError {errMsg = "Couldn't match expected type `GHC.Types.Float'\n            with actual type `GHC.Types.Char'"}]

【讨论】:

  • 这太棒了,自从托马斯发表评论以来,我一直在玩提示;我的程序最终将函数转换为值列表,因此我的实现完全跳过了转换为函数而只生成一个列表。
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 2012-06-29
  • 1970-01-01
  • 1970-01-01
  • 2016-06-25
  • 1970-01-01
  • 1970-01-01
  • 2021-08-03
相关资源
最近更新 更多