Search code examples
javascriptffipurescript

purescript FFI types to safely import javascript functions


Trying out the purescript FFI, and following the "Purescript By Example" book, I have created a JS file to get the head of an array:

exports.head = function(arr) {
  return arr[0];
};

And in purescript I declare a new Undefined data for the type signature of head to indicate the undefined returned when the array is empty:

foreign import data Undefined :: Type -> Type
foreign import head :: forall a. Array a -> Undefined a

Now, how do I use a value of type Undefined a? What function do I need to define to extract the a so I can use it elsewhere? The example in the book follows by just defining a function:

foreign import isUndefined :: forall a. Undefined a -> Boolean

as:

exports.isUndefined = function(value) {
  return value === undefined;
};

but I need something like:

foreign import getFromUndefined :: forall a. Undefined a -> a

Is it possible to write that function in JS, and in that case, what to return when the Undefined a is really undefined? Or alternatively, can I redefine the type Undefined a to allow patern matching over it to extract the a?


Solution

  • You could implement something like

    foreign import fromUndefinedWithDefault :: forall a. a -> Undefined a -> a
    

    instead by reusing what you did to define isUndefined.

    The type you wrote cannot be implemented because safely, because I could use it to define

    bad :: Void
    bad = getFromUndefined (head [])