Calling Haskell functions from Python

后端 未结 6 2021
醉话见心
醉话见心 2020-12-04 18:22

I want to use some Haskell libraries (e.g. Darcs, Pandoc) from Python, but it seems there’s no direct foreign function interface to Haskell in Python. Is there any way to do

6条回答
  •  忘掉有多难
    2020-12-04 18:42

    Another option is hyphen, which can be found here. Basic usage looks something like:

    >>> import hyphen, hs.Prelude
    >>> hs.Prelude.sum([1,2,3]) # list converted to Haskell list
    6
    >>> hs.Prelude.drop(5, "Hello, world")
    ", world"
    >>> hs.Prelude.drop(1, [1,2,3])
    
    >>> list(hs.Prelude.drop(1, [1,2,3]))   # Convert back to Python list
    [2, 3]
    

    This seems to be a less lightweight solution than some of the other options in other answers.

    In return for the extra weight, you seem to get a full bridge from Haskell to Python. Whereas HaPy and github.com/nh2/call-haskell-from-anything only allow you to use a Haskell function from Python if that Haskell function has all its arguments from fairly basic types and returns a fairly basic type, hyphen seems to let you use arbitrary functions. It can do this because it introduces into python a type representing an arbitrary object on the Haskell heap.

    These 'haskell objects viewed from python' behave fairly nicely as python objects. For example Haskell Maps behave a bit like dictionaries:

    >>> import hs.Data.Map
    >>> my_map = hs.Data.Map.fromList([(1, 'Hello'), (2, 'World')])
    >>> my_map[1]
    'Hello'
    >>> print(sorted([key for key in my_map]))
    [1, 2]
    

    See the readme for many more examples!

    It also seems to handle various fancy things like converting exceptions between Haskell and Python.

提交回复
热议问题