【发布时间】:2013-10-30 14:53:12
【问题描述】:
我对 Haskell 有点陌生,正在做一个项目,我有以下代码:
data Nested a = Elem a | Nested [Nested a] deriving (Eq, Show)
data Symbol a = Value a | Transformation (a -> a -> a) deriving (Show)
toSymbol :: [Char] -> Nested (Symbol Integer)
toSymbol x
|all isDigit x = Elem (Value (strToInt x))
|x == "+" = Elem (Transformation (\x y -> x + y))
有没有办法避免这个函数的类型被限制为嵌套(符号整数)?我想用 Symbol 来表示许多不同的类型,并有一个函数 toSymbol 类似于以下内容:
toSymbol x
|x == "1" = Elem (Value 1)
|x == "+" = Elem (Transformation (\x y -> x + y))
|x == "exampleword" = Elem (Value "word")
|x == "concatenate()" = Elem (Transformation concatTwoStrings)
我不知道这样的函数的类型签名可能是什么。我能做些什么来获得类似的功能吗?
【问题讨论】:
-
不,这只能通过完全绕过类型系统来工作。你想为这类东西使用动态语言。 Haskell 方法首先不是从字符串开始,而是从作为 DSL 的 Haskell 代码开始;然后编译器可以静态推断类型,并且您可以获得完整的类型安全性,而无需太多额外的语法。或者从某种自定义树 ADT 结构开始。但不是来自纯字符串!如果您需要将一些数据保存在文件中,there's libraries for that,但我不会打扰细节。