0

我正在尝试将以下伪代码转换为 Haskell:

stringA = "ABCD"
stringB = "EFGH"
stringC = "ICJK"

function myFunction(String x) {

     otherFunction(x)

}

现在,在 Haskell 我有

 stringA = "ABCD";
 stringB = "EFGH";
 stringC = "ICJK";


test :: Int
test x = if x == 1 then otherFunction(??) else ...

当使用 x =“stringA”调用 test 时,如何确保 otherFunction 将 stringA 作为参数?

谢谢!:)

4

2 回答 2

7
test :: Int
test x = if x == 1 then otherFunction stringA else ...

当然,这是错误的,因为 test 需要一个参数,所以它的类型必须始终包含(至少)一个(->)。但这不是手头的问题。奇怪的是,您声称您的伪代码函数需要一个字符串参数,这test :: String -> ...在 Haskell 中看起来很像。但是你显然给它一个 Int 作为它的第一个参数,这意味着它的类型应该是test :: Int -> ...

这是我对您的伪代码的翻译:

stringA = "ABCD"
stringB = "EFGH"
stringC = "ICJK"

test x = otherFunction x
于 2013-11-10T00:42:43.190 回答
0
test "stringA" = otherFunction stringA
test "stringB" = otherFunction stringB
test "stringB" = otherFunction stringB
-- etc...

正如您可以想象的那样,对于超过 3 或 4 个案例来说,这将是一件痛苦的事情。将字符串作为键/值对存储在列表中怎么样?

test strIn = (liftM otherFunction) lookup strIn dict
   where dict = 
        [("stringA", "ABCD"), ("stringB", "EFGH"), ("stringC", "ICJK")]

通常,无法在运行时将字符串转换为函数引用。

于 2013-11-10T11:18:54.587 回答