在Haskell中访问外部变量

时间:2013-11-10 00:40:19

标签: haskell

我正在尝试将以下伪代码转换为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作为参数?

谢谢! :)

2 个答案:

答案 0 :(得分:7)

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

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

这是我的伪代码翻译:

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

test x = otherFunction x

答案 1 :(得分: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")]

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