2017-07-19 55 views
2

我试图用FFI导入下面的JavaScript函数到PureScript映射0参数的JavaScript函数:如何PureScript FFI

function getGreeting() { 
    return "Hi, welcome to the show." 
} 

,但我不知道该类型应该是什么。最近我得到的是这样的:

foreign import getGreeting :: Unit -> String 

我想getGreeting留的功能,而不是将其转换为一个常数。

有没有更好的方法来编写类型?我想看看我定义了一个虚拟函数PureScript做什么PureScript本身与该类型的签名:

var getGreeting = function (v) { 
    return "Hi, welcome to the show."; 
}; 

有没有摆脱没有正在使用的v参数的方法吗?

TIA

+1

“我希望getGreeting保留一个函数,而不是将其转换为常量”我认为这个函数是一个常量。为什么你想要有这样的功能? – paluh

+0

如果您正在使用某种副作用,或者您依靠某种外部状态来生成或获取此值,我认为您可以将此函数类型设置为getGreeting :: forall eff。 Eff(SOME_EFFECT | eff)字符串。 – paluh

+0

@paluh我不想更改'getGreeting',因为它不是我的源代码,现在应该被认为是不可更改的。另外也没有副作用,所以'Eff'类型是不可取的。 –

回答

2

Unit -> String是一个非常好的类型,或者可能是forall a. a -> String。后一种类型可能看起来过于宽容,但我们肯定知道a由于参数性而未被使用,所以该函数仍然必须是恒定的。

1

实在是有用的包purescript-functions这可能是在这种情况下有益的,如果你真的必须从Purescript调用此函数,它是(因为我认为它IS真的只是一个常数)你可以试试:

module Main where 

import Prelude 
import Control.Monad.Eff (Eff) 
import Control.Monad.Eff.Console (CONSOLE, log) 
import Data.Function.Uncurried (Fn0, runFn0) 

foreign import getString ∷ Fn0 String 

main :: forall e. Eff (console :: CONSOLE | e) Unit 
main = do 
    log (runFn0 getString) 

我创建这个简单的JavaScript模块,使这个例子可以测试:

/* global exports */ 
"use strict"; 

// module Main 

exports.getString = function() { 
    return "my constant string ;-)"; 
}; 
+0

谢谢paluh。很高兴知道'Data.Function.Uncurried'。我决定从gb中得到答案,因为对于那么简单的东西,给出'Unit - > String'类型似乎是最简单的解决方案。 –

+0

酷! 'Data.Function.Uncurried'可以特别有用,当你在javascript方面有函数WITH(多个)参数并且不想包装它们来写入FFI绑定时;-) – paluh