Upcoming SlideShare
×

1,175 views

Published on

RubyからHaslekkで記述した関数を呼び出すサンプルの説明です。

Published in: Technology, Education
0 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

Views
Total views
1,175
On SlideShare
0
From Embeds
0
Number of Embeds
8
Actions
Shares
0
9
0
Likes
0
Embeds 0
No embeds

No notes for slide
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n
• \n

1. 1. �
2. 2. foreign import ccall ”math.h sin” sin :: CDouble -> CDoubleforeign export ccall ”fact” fact :: CInt -> CInt
3. 3.
4. 4. == factorial.hs ==Module Factorial whereimport Foreign.C.Typesforeign export ccall ”factorial” factorial :: CInt -> Cintfactorial 0 = 1factorial x = x * factorial(x-1)
5. 5. == main.c ==#include <stdio.h>#include “factorial_stub.h”int main(int argc, char* argv[]){ hs_init(&argc, &argv); printf(“%dn”, fact(5)); hs_exit(); return 0;}
6. 6. \$ ghc -shared -dynamic... ( )
7. 7. #include <ruby.h>#include "factorial_stub.h"static VALUE rb_factorial(VALUE self, VALUE val){ return UINT2NUM(factorial(NUM2UINT(val)));}void Init_factorial(void){ hs_init(NULL, NULL);// Haskell .. rb_define_module_function(rb_mMath, "factorial", RUBY_METHOD_FUNC(rb_factorial), 1);}
8. 8. (gem install )\$ irb -r factorial/factorialirb(main):001:0> Math.factorial 4=> 24
9. 9. foreign export ccall ”factorial”factorial :: CInt -> CIntCInt -229 +229-1 9 362,880 10 3,628,800 15 1.30767E+12
10. 10. \$ cd `ghc --print-libdir` �
11. 11. require rbconfigTARGET = factorialC_SRC = %w{ main.c }HS_SRC = %w{ factorial.hs }HS_LIBS = %w{ base integer-gmp ghc-prim }CONF = RbConfig::MAKEFILE_CONFIGVALS = %w{prefix includedir RUBY_BASE_NAME ruby_versionrubyhdrdir arch MKDIR_P INSTALL INSTALL_PROGRAM}.map{|k| "#{k}=#{CONF[k]}" }.join("n")GHC_LIBDIR=`ghc --print-libdir`.stripFLAGS = "FLAGS=-I\$(rubyhdrdir) -I\$(rubyhdrdir)/\$(arch) -shared -dynamic -no-hs-main -lHSrts -lffin" + "FLAGS+=-no-auto-link-packages -I#{GHC_LIBDIR}/include -L#{GHC_LIBDIR}n" + HS_LIBS.map{|l| FLAGS+= + `ghc-pkg describe #{l}|sed -ne s/library-dirs: /-L/p;s/hs-libraries: /-l/p;`.gsub(/n/, ) }.join("n") + "nFLAGS+=-lgmpn"
12. 12. File.open("Makefile", "w") {|f| f.puts <<__MAKEFILE__TARGET=#{TARGET}.#{CONF[DLEXT]}HS_SRC=#{HS_SRC.join( )}C_SRC=#{C_SRC.join( )}#{VALS}#{FLAGS}STUB=\$(HS_SRC:.hs=_stub.o)all : \$(TARGET)\$(STUB) : \$(HS_SRC) ghc \$<\$(TARGET) : \$(C_SRC) \$(STUB) \$(HS_SRC:.hs=.o) ghc -o \$@ \$^ \$(FLAGS)install: \$(MKDIR_P) ../lib/#{TARGET}/ \$(INSTALL_PROGRAM) \$(TARGET) ../lib/#{TARGET}/clean: rm -f \$(TARGET) \$(C_SRC:.c=.o) \$(HS_SRC:.hs=.hi) \$(HS_SRC:.hs=.o) \$(HS_SRC:.hs=_stub.)*__MAKEFILE__}
13. 13. ��
14. 14.