Re: [Haskell-cafe] C++
This array is for dynamic programming. You can diagonalize it into a list and use technique similar to the Fibonacci numbers. The resulting solution should be purely declarative. 2012/12/11 mukesh tiwari mukeshtiwari.ii...@gmail.com: Hello All I am trying to transform this C++ code in Haskell. In case any one interested this is solution of SPOJ problem. #includecstdio #includeiostream #includecstring using namespace std; int memo[1100][1100] ; int recurse( int h , int a , int cnt , bool flag ) { if ( h = 0 || a = 0 ) return cnt ; if ( memo[h][a] ) return memo[h][a] ; if ( flag ) memo[h][a] = recurse ( h + 3 , a + 2 , cnt + 1 , !flag ) ; else memo[h][a] = max ( memo[h][a] , max ( recurse ( h - 5 , a - 10 , cnt + 1 , !flag ) , recurse ( h - 20 , a + 5 , cnt + 1 , !flag ) ) ) ; return memo[h][a]; } int main() { int n , a , b ; scanf( %d, n ); for(int i = 0 ; i n ; i++) { memset ( memo , 0 , sizeof memo ) ; scanf(%d%d, a , b ); printf(%d\n , recurse( a , b , -1 , 1 )); if( i != ( n - 1 ) ) printf(\n); } } I am stuck with that memo[1100][1100] is global variable so I tried to solve this problem using state monad ( Don't know if its correct approach or not ) but it certainly does not seem correct to me. Till now I came up with code. Could some one please tell me how to solve this kind of problem ( Generally we have a global variable either multi dimensional array or map and we store the best values found so far in the table ). import qualified Data.Map.Strict as SM import Control.Monad.State {-- funsolve_WF :: Int - Int - Int - Int funsolve_WF h a cnt | h = 0 || a = 0 = cnt | otherwise = funsolve_Air h a ( cnt + 1 ) funsolve_Air :: Int - Int - Int - Int funsolve_Air h a cnt = max ( funsolve_WF ( h + 3 - 5 ) ( a + 2 - 10 ) cnt' ) ( funsolve_WF ( h + 3 - 20 ) ( a + 2 + 5 ) cnt' ) where cnt' = cnt + 1 --} funSolve :: Int - Int - Int - Bool - State ( SM.Map ( Int , Int ) Int ) Int funSolve hl am cnt f | hl = 0 am = 0 = return cnt | otherwise = do mp - get case () of _| SM.member ( hl , am ) mp - return mp SM.! ( hl , am ) | f - do --here I have to insert the value return by function funSolve ( hl + 3 ) ( am + 2 ) ( cnt + 1 ) ( not f ) to map whose key is ( hl , am ) let k = evalState ( funSolve ( hl + 3 ) ( am + 2 ) ( cnt + 1 ) ( not f ) ) mp modify ( SM.insert ( hl , am ) k ) | otherwise - do do let k_1 = evalState ( funSolve ( hl - 5 ) ( am - 10 ) ( cnt + 1 ) ( not f ) ) mp k_2 = evalState ( funSolve ( hl - 20 ) ( am + 5 ) ( cnt + 1 ) ( not f ) ) mp k_3 = mp SM.! ( hl , am ) modify ( SM.insert ( hl , am ) ( maximum [ k_1 , k_2 , k_3 ] ) ) Regards Mukesh Tiwari ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++
If you're trying to memoize a recursive algorithm with a global array of previous states, you could use the marvellous MemoTrie package [1]. It lets you write your algorithm recursively, while getting all the benefits of memoization! Here's an example with the fibonacci function: fib :: Int - Integer fib 0 = 1 fib 1 = 1 fib n = memofib (n - 2) + memofib (n - 1) memofib :: Int - Integer memofib = memo fib memofib 113 -- runs in O(n), with (permanent!) memory usage also at O(n). - Clark [1] http://hackage.haskell.org/package/MemoTrie On Tue, Dec 11, 2012 at 2:59 PM, Serguey Zefirov sergu...@gmail.com wrote: This array is for dynamic programming. You can diagonalize it into a list and use technique similar to the Fibonacci numbers. The resulting solution should be purely declarative. 2012/12/11 mukesh tiwari mukeshtiwari.ii...@gmail.com: Hello All I am trying to transform this C++ code in Haskell. In case any one interested this is solution of SPOJ problem. #includecstdio #includeiostream #includecstring using namespace std; int memo[1100][1100] ; int recurse( int h , int a , int cnt , bool flag ) { if ( h = 0 || a = 0 ) return cnt ; if ( memo[h][a] ) return memo[h][a] ; if ( flag ) memo[h][a] = recurse ( h + 3 , a + 2 , cnt + 1 , !flag ) ; else memo[h][a] = max ( memo[h][a] , max ( recurse ( h - 5 , a - 10 , cnt + 1 , !flag ) , recurse ( h - 20 , a + 5 , cnt + 1 , !flag ) ) ) ; return memo[h][a]; } int main() { int n , a , b ; scanf( %d, n ); for(int i = 0 ; i n ; i++) { memset ( memo , 0 , sizeof memo ) ; scanf(%d%d, a , b ); printf(%d\n , recurse( a , b , -1 , 1 )); if( i != ( n - 1 ) ) printf(\n); } } I am stuck with that memo[1100][1100] is global variable so I tried to solve this problem using state monad ( Don't know if its correct approach or not ) but it certainly does not seem correct to me. Till now I came up with code. Could some one please tell me how to solve this kind of problem ( Generally we have a global variable either multi dimensional array or map and we store the best values found so far in the table ). import qualified Data.Map.Strict as SM import Control.Monad.State {-- funsolve_WF :: Int - Int - Int - Int funsolve_WF h a cnt | h = 0 || a = 0 = cnt | otherwise = funsolve_Air h a ( cnt + 1 ) funsolve_Air :: Int - Int - Int - Int funsolve_Air h a cnt = max ( funsolve_WF ( h + 3 - 5 ) ( a + 2 - 10 ) cnt' ) ( funsolve_WF ( h + 3 - 20 ) ( a + 2 + 5 ) cnt' ) where cnt' = cnt + 1 --} funSolve :: Int - Int - Int - Bool - State ( SM.Map ( Int , Int ) Int ) Int funSolve hl am cnt f | hl = 0 am = 0 = return cnt | otherwise = do mp - get case () of _| SM.member ( hl , am ) mp - return mp SM.! ( hl , am ) | f - do --here I have to insert the value return by function funSolve ( hl + 3 ) ( am + 2 ) ( cnt + 1 ) ( not f ) to map whose key is ( hl , am ) let k = evalState ( funSolve ( hl + 3 ) ( am + 2 ) ( cnt + 1 ) ( not f ) ) mp modify ( SM.insert ( hl , am ) k ) | otherwise - do do let k_1 = evalState ( funSolve ( hl - 5 ) ( am - 10 ) ( cnt + 1 ) ( not f ) ) mp k_2 = evalState ( funSolve ( hl - 20 ) ( am + 5 ) ( cnt + 1 ) ( not f ) ) mp k_3 = mp SM.! ( hl , am ) modify ( SM.insert ( hl , am ) ( maximum [ k_1 , k_2 , k_3 ] ) ) Regards Mukesh Tiwari ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ Parser?
I have written a C++ parser in Scheme, with a Parsec-style parser combinator library. It can parse a large portion of C++ and I use it to do structural comparison between ASTs. I made some macros so that the parser combinators look like the grammar itself. It's code is at: http://github.com/yinwang0/ydiff/blob/master/parse-cpp.ss A demo of the parse tree based comparison tool is at: http://www.cs.indiana.edu/~yw21/demos/d8-3404-d8-8424.html The bit of information I can tell you about parsing C++: - C++'s grammar is not that bad if you see the consistency in it. Parsing a major portion of C++ is not hard. I made the parser in two days. It can parse most of Google's V8 Javascript compiler code. I just need to fix some corner cases later. - It is better to delay semantic checks to a later stage. Don't put those into the parser. Parse a larger language first, and then walk the parse tree to eliminate semantically wrong programs. - Don't try translating from the formal grammar or parser generator files for C++. They contain years of bugs and patches and you will probably be confused looking at them. I wrote the parser just by looking at some example C++ programs. Cheers, Yin On Tue, Jan 24, 2012 at 5:06 AM, Christopher Brown cm...@st-andrews.ac.uk wrote: Hi, I have stumbled across language-c on hackage and I was wondering if anyone is aware if there exists a full C++ parser written in Haskell? Many thanks, Chris. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ Parser?
On Wed, Feb 1, 2012 at 12:42 PM, Yin Wang yinwa...@gmail.com wrote: I have written a C++ parser in Scheme, with a Parsec-style parser combinator library. It can parse a large portion of C++ and I use it to do structural comparison between ASTs. I made some macros so that the parser combinators look like the grammar itself. It's code is at: http://github.com/yinwang0/ydiff/blob/master/parse-cpp.ss A demo of the parse tree based comparison tool is at: http://www.cs.indiana.edu/~yw21/demos/d8-3404-d8-8424.html The bit of information I can tell you about parsing C++: Thank you for the interesting response and example code (that I haven't had a chance to look at yet). How much support do you have for templates? Jason ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ Parser?
I haven't dealt explicitly with templates. I treat them as type parameters (element $type-parameter). I don't check that they have been declared at all. As explained, these are semantic checks and should be deferred until type checking stage ;-) Cheers, Yin On Wed, Feb 1, 2012 at 4:07 PM, Jason Dagit dag...@gmail.com wrote: On Wed, Feb 1, 2012 at 12:42 PM, Yin Wang yinwa...@gmail.com wrote: I have written a C++ parser in Scheme, with a Parsec-style parser combinator library. It can parse a large portion of C++ and I use it to do structural comparison between ASTs. I made some macros so that the parser combinators look like the grammar itself. It's code is at: http://github.com/yinwang0/ydiff/blob/master/parse-cpp.ss A demo of the parse tree based comparison tool is at: http://www.cs.indiana.edu/~yw21/demos/d8-3404-d8-8424.html The bit of information I can tell you about parsing C++: Thank you for the interesting response and example code (that I haven't had a chance to look at yet). How much support do you have for templates? Jason ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ Parser?
On Tue, Jan 24, 2012 at 4:06 AM, Christopher Brown cm...@st-andrews.ac.uk wrote: Hi, I have stumbled across language-c on hackage and I was wondering if anyone is aware if there exists a full C++ parser written in Haskell? I'm not aware of one. When it comes to parsing C++, I've always been a fan of this essay: http://www.nobugs.org/developer/parsingcpp/ It's a hobbyist's tale of looking into parsing C++ and then an explanation of why he gave up. It's older, so perhaps the state-of-the-art has advanced since then. Antoine ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ Parser?
On 24 Jan 2012, at 11:06, Christopher Brown wrote: I have stumbled across language-c on hackage and I was wondering if anyone is aware if there exists a full C++ parser written in Haskell? There is a yaccable grammar http://www.parashift.com/c++-faq-lite/compiler-dependencies.html#faq-38.11 You might run it through a parser generator that outputs Haskell code. http://www.haskell.org/haskellwiki/Applications_and_libraries/Compiler_tools Hans ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ Parser?
On Tue, Jan 24, 2012 at 2:06 AM, Christopher Brown cm...@st-andrews.ac.uk wrote: Hi, I have stumbled across language-c on hackage and I was wondering if anyone is aware if there exists a full C++ parser written in Haskell? I don't think one exists. I've heard it's quite difficult to get template parsing working in an efficient manner. My understanding is that real C++ compilers use the Edison Design Group's parser: http://www.edg.com/index.php?location=c_frontend For example, the Intel C++ compiler uses the edg front-end: http://en.wikipedia.org/wiki/Intel_C%2B%2B_Compiler I thought even microsoft's compiler (which is surprisingly c++ compliant) uses it but I can't find details on google about that. There is at least one open source project using it, rose, so it's not unthinkingable to use it from Haskell: http://rosecompiler.org/ Rose has had working haskell bindings in the past but they have bit rotted a bit. With rose you get support for much more than parsing C++. You also get C and Fortran parsers as well as a fair bit of static analysis. The downside is that rose is a big pile of C++ itself and is hard to compile on some platforms. If you made a BSD3 licensed, fully functional, efficient C++ parser that would be great. If you made it so that it preserves comments and the input well enough to do source to source transformations (unparsing) that would be very useful. I often wish I had rose implemented in Haskell instead of C++. Jason ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ Parser?
Hi Everyone, Thanks for everyone's kind responses: very helpful so far! I fully appreciate and understand how difficult writing a C++ parser is. However I may need one for our new Paraphrase project, where I may be targeting C++ for writing a refactoring tool. Obviously I don't want to start writing one myself, hence I was asking if anyone new about an already existing implementation. Rose looks interesting, I'll check that out, thanks! Chris. On 24 Jan 2012, at 14:40, Jason Dagit wrote: On Tue, Jan 24, 2012 at 2:06 AM, Christopher Brown cm...@st-andrews.ac.uk wrote: Hi, I have stumbled across language-c on hackage and I was wondering if anyone is aware if there exists a full C++ parser written in Haskell? I don't think one exists. I've heard it's quite difficult to get template parsing working in an efficient manner. My understanding is that real C++ compilers use the Edison Design Group's parser: http://www.edg.com/index.php?location=c_frontend For example, the Intel C++ compiler uses the edg front-end: http://en.wikipedia.org/wiki/Intel_C%2B%2B_Compiler I thought even microsoft's compiler (which is surprisingly c++ compliant) uses it but I can't find details on google about that. There is at least one open source project using it, rose, so it's not unthinkingable to use it from Haskell: http://rosecompiler.org/ Rose has had working haskell bindings in the past but they have bit rotted a bit. With rose you get support for much more than parsing C++. You also get C and Fortran parsers as well as a fair bit of static analysis. The downside is that rose is a big pile of C++ itself and is hard to compile on some platforms. If you made a BSD3 licensed, fully functional, efficient C++ parser that would be great. If you made it so that it preserves comments and the input well enough to do source to source transformations (unparsing) that would be very useful. I often wish I had rose implemented in Haskell instead of C++. Jason ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ Parser?
On Tue, Jan 24, 2012 at 6:54 AM, Christopher Brown cm...@st-andrews.ac.uk wrote: Hi Everyone, Thanks for everyone's kind responses: very helpful so far! I fully appreciate and understand how difficult writing a C++ parser is. However I may need one for our new Paraphrase project, where I may be targeting C++ for writing a refactoring tool. Obviously I don't want to start writing one myself, hence I was asking if anyone new about an already existing implementation. Rose looks interesting, I'll check that out, thanks! I did some more digging after sending my email. I didn't learn about GLR parser when I was in school, but that seems to be what the cool compilers use these days. Then I discovered that Happy supports GLR, that is happy! Next I found that GLR supposedly makes C++ parsing much easier than LALR, The reason I wrote Elkhound is to be able to write a C++ parser. The parser is called Elsa, and is included in the distribution below. The elsa documentation should give you a flavor for what needs to be done when making sense of C++: http://scottmcpeak.com/elkhound/sources/elsa/index.html NB: I don't think it's been seriously worked on since 2005 so I assume it doesn't match the latest C++ spec. The grammar that elsa parses is here, one warning is that it doesn't reject all invalid programs (eg., it errs on the side of accepting too much): http://scottmcpeak.com/elkhound/sources/elsa/cc.gr I think the path of least resistance is pure rose without the haskell support. Having said that, I think the most fun direction would be converting the elsa grammar to happy. It's just that you'll have a lot of work (read: testing, debugging, performance tuning, and then adding vendor features) to do. One side benefit is that you'll know much more about the intricacies of C++ when you're done than if you use someone else's parser. Jason ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ Parser?
Hi Jason, Thanks very much for you thoughtful response. I am intrigued about the Happy route: as I have never really used Happy before, am I right in thinking I could take the .gr grammar, feed it into Happy to generate a parser, or a template for a parser, and then go from there? Chris. On 24 Jan 2012, at 15:16, Jason Dagit wrote: On Tue, Jan 24, 2012 at 6:54 AM, Christopher Brown cm...@st-andrews.ac.uk wrote: Hi Everyone, Thanks for everyone's kind responses: very helpful so far! I fully appreciate and understand how difficult writing a C++ parser is. However I may need one for our new Paraphrase project, where I may be targeting C++ for writing a refactoring tool. Obviously I don't want to start writing one myself, hence I was asking if anyone new about an already existing implementation. Rose looks interesting, I'll check that out, thanks! I did some more digging after sending my email. I didn't learn about GLR parser when I was in school, but that seems to be what the cool compilers use these days. Then I discovered that Happy supports GLR, that is happy! Next I found that GLR supposedly makes C++ parsing much easier than LALR, The reason I wrote Elkhound is to be able to write a C++ parser. The parser is called Elsa, and is included in the distribution below. The elsa documentation should give you a flavor for what needs to be done when making sense of C++: http://scottmcpeak.com/elkhound/sources/elsa/index.html NB: I don't think it's been seriously worked on since 2005 so I assume it doesn't match the latest C++ spec. The grammar that elsa parses is here, one warning is that it doesn't reject all invalid programs (eg., it errs on the side of accepting too much): http://scottmcpeak.com/elkhound/sources/elsa/cc.gr I think the path of least resistance is pure rose without the haskell support. Having said that, I think the most fun direction would be converting the elsa grammar to happy. It's just that you'll have a lot of work (read: testing, debugging, performance tuning, and then adding vendor features) to do. One side benefit is that you'll know much more about the intricacies of C++ when you're done than if you use someone else's parser. Jason ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ Parser?
On Tue, Jan 24, 2012 at 8:40 AM, Christopher Brown cm...@st-andrews.ac.uk wrote: Hi Jason, Thanks very much for you thoughtful response. I am intrigued about the Happy route: as I have never really used Happy before, am I right in thinking I could take the .gr grammar, feed it into Happy to generate a parser, or a template for a parser, and then go from there? That's the basic idea although the details will be harder than that. Happy is a parser generator (like Bison, Yacc, and ANTLR). Happy and elsa will have very different syntax for their grammar definitions. You could explore taking the elkhound source and instead of generating C++ you could generate the input for happy, if that makes sense. A translation by hand would probably be easiest. I would highly recommend making a few toy parsers with Happy + Alex (alex is like lex or flex) to get a feel for it before trying to use the grammar from elsa. A quick google search pointed me at these examples: http://darcs.haskell.org/happy/examples/ Jason ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ Parser?
On Tue, Jan 24, 2012 at 2:06 AM, Christopher Brown cm...@st-andrews.ac.ukwrote: I have stumbled across language-c on hackage and I was wondering if anyone is aware if there exists a full C++ parser written in Haskell? Check out clang: http://clang.llvm.org/ and http://hackage.haskell.org/package/LibClang The clang API is in C++ and will do just about everything you'd ever want to do with C/ObjC/C++ source. -n ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ Parser?
There is also the DMS from Ira Baxter's company Semantic Design's. This is an industry proven refactoring framework that handles C++ as well as other languages. I think the Antlr C++ parser may have advanced since the article Antoine Latter link to, but personally I'd run a mile before trying to do any source transformation of C++ even if someone were waving a very large cheque at me. On 24 January 2012 14:54, Christopher Brown cm...@st-andrews.ac.uk wrote: Hi Everyone, Thanks for everyone's kind responses: very helpful so far! I fully appreciate and understand how difficult writing a C++ parser is. However I may need one for our new Paraphrase project, where I may be targeting C++ for writing a refactoring tool. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ Parser?
Hi all, Just to add to the list - Qt Creator contains a pretty nice (and incremental) C++ parser. Cheers, Dave On Wed, Jan 25, 2012 at 5:06 AM, Stephen Tetley stephen.tet...@gmail.comwrote: There is also the DMS from Ira Baxter's company Semantic Design's. This is an industry proven refactoring framework that handles C++ as well as other languages. I think the Antlr C++ parser may have advanced since the article Antoine Latter link to, but personally I'd run a mile before trying to do any source transformation of C++ even if someone were waving a very large cheque at me. On 24 January 2012 14:54, Christopher Brown cm...@st-andrews.ac.uk wrote: Hi Everyone, Thanks for everyone's kind responses: very helpful so far! I fully appreciate and understand how difficult writing a C++ parser is. However I may need one for our new Paraphrase project, where I may be targeting C++ for writing a refactoring tool. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C][enums][newbie] What is natural Haskell representation of such enum?
2012/1/22 Данило Глинський abcz2.upr...@gmail.com What is natural Haskell representation of such enum? enum TypeMask { UNIT, GAMEOBJECT, CREATURE_OR_GAMEOBJECT = UNIT | GAMEOBJECT }; I don't think that definition makes any sense in C, because UNIT is 0, so UNIT | GAMEOBJECT == GAMEOBJECT == 1 Nevertheless, in Haskell something vaguely similar might be: data TypeMask = UNIT | GAMEOBJECT | CREATURE_OR_GAMEOBJECT // 1-byte flaged enum enum TypeMask { // ... UNIT= 0x0004, GAMEOBJECT = 0x0008, // ... CREATURE_OR_GAMEOBJECT = UNIT | GAMEOBJECT WORLDOBJECT = UNIT | PLAYER | GAMEOBJECT | DYNAMICOBJECT | CORPSE // ... even more enum combos ... }; import Data.Bits data TypeMask = UNIT | GAMEOBJECT | CREATURE_OR_GAMEOBJECT | WORLDOBJECT instance Enum TypeMask where fromEnum UNIT = 0x4 fromEnum GAMEOBJECT = 0x8 fromEnum CREATURE_OR_GAMEOBJECT = fromEnum UNIT .|. fromEnum GAMEOBJECT fromEnum WORLDOBJECT = fromEnum UNIT .|. fromEnum PLAYER .|. fromEnum GAMEOBJECT .|. fromEnum DYNAMICOBJECT .|. fromEnum CORPSE toEnum 0x4 = UNIT toEnum 0x8 = GAMEOBJECT toEnum _ = error unspecified enumeration value of type TypeMask isCreatureOrGameObject :: Int - Bool isCreatureOrGameObject x = (x .|. fromEnum CREATURE_OR_GAMEOBJECT) /= 0 isWorldObject :: Int - Bool isWorldObject x = (x .|. fromEnum WORLDOBJECT) /= 0 -- But fundamentally, this is not an idiomatic Haskell way of doing things. -- The other posts in this thread have shown more Haskell-ish translations. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C][enums][newbie] What is natural Haskell representation of such enum?
Thanks. This and previous email are answers to question I asked. But not the answer to question I mean. I'll describe the whole task, as Yves Parès suggested. I'm trying to convert C++ code to Haskell. I have such hierarchy: class Object, class Item : Object, class Container : Item. Another one example: class Unit : Object, class Player : Unit. Each constructor do things like this: Object::Object() { objectType= TYPEMASK_OBJECT; // ... lots of code ... } Item::Item() { objectType |= TYPEMASK_ITEM; // ... } Container::Container(): Item() { objectType |= (TYPEMASK_ITEM | TYPEMASK_CONTAINER); // ... } What is objectType? This field is used when a networksend packet is created. In the packet it is 1 byte of flags, so it is in object hierarchy. So the question was: what type should objectType field have in Haskell? I think it must not mimic enum. What the structure have I to use? There is one more problem - there may be lots of objects, lots of, so memory efficiency is also suggested. And side question: what to do with classes? =) Maybe there is simple rule to convert OO hierarchy to FP. 23 січня 2012 р. 12:15 Malcolm Wallace malcolm.wall...@me.com написав: 2012/1/22 Данило Глинський abcz2.upr...@gmail.com What is natural Haskell representation of such enum? enum TypeMask { UNIT, GAMEOBJECT, CREATURE_OR_GAMEOBJECT = UNIT | GAMEOBJECT }; I don't think that definition makes any sense in C, because UNIT is 0, so UNIT | GAMEOBJECT == GAMEOBJECT == 1 Nevertheless, in Haskell something vaguely similar might be: data TypeMask = UNIT | GAMEOBJECT | CREATURE_OR_GAMEOBJECT // 1-byte flaged enum enum TypeMask { // ... UNIT= 0x0004, GAMEOBJECT = 0x0008, // ... CREATURE_OR_GAMEOBJECT = UNIT | GAMEOBJECT WORLDOBJECT = UNIT | PLAYER | GAMEOBJECT | DYNAMICOBJECT | CORPSE // ... even more enum combos ... }; import Data.Bits data TypeMask = UNIT | GAMEOBJECT | CREATURE_OR_GAMEOBJECT | WORLDOBJECT instance Enum TypeMask where fromEnum UNIT = 0x4 fromEnum GAMEOBJECT = 0x8 fromEnum CREATURE_OR_GAMEOBJECT = fromEnum UNIT .|. fromEnum GAMEOBJECT fromEnum WORLDOBJECT = fromEnum UNIT .|. fromEnum PLAYER .|. fromEnum GAMEOBJECT .|. fromEnum DYNAMICOBJECT .|. fromEnum CORPSE toEnum 0x4 = UNIT toEnum 0x8 = GAMEOBJECT toEnum _ = error unspecified enumeration value of type TypeMask isCreatureOrGameObject :: Int - Bool isCreatureOrGameObject x = (x .|. fromEnum CREATURE_OR_GAMEOBJECT) /= 0 isWorldObject :: Int - Bool isWorldObject x = (x .|. fromEnum WORLDOBJECT) /= 0 -- But fundamentally, this is not an idiomatic Haskell way of doing things. -- The other posts in this thread have shown more Haskell-ish translations. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C][enums][newbie] What is natural Haskell representation of such enum?
If you want a simple translation, use Word8 (from Data.Word) for the type and use Data.Bits for operations on it just like in C++. This would offer you storage efficiency (if stored as a strict field). If you want idiomatic Haskell, constructor of the form: data ObjectType = Object | Item | Container | Unit | Player, etc. Then simply put intelligence into the `isContainer` or `toWord8`, etc. translations. This latter approach will be more extensible in the long run, since you might find you want some parameterized object types. Re: OO Classes and Haskell If your classes are more like `interfaces`, you could use Typeclasses to model them. Otherwise, look into OOHaskell. But I think your program architecture will simply be different in idiomatic Haskell than in idiomatic C++. Regards, Dave On Mon, Jan 23, 2012 at 1:14 PM, Daniel Hlynskyi abcz2.upr...@gmail.comwrote: Thanks. This and previous email are answers to question I asked. But not the answer to question I mean. I'll describe the whole task, as Yves Parès suggested. I'm trying to convert C++ code to Haskell. I have such hierarchy: class Object, class Item : Object, class Container : Item. Another one example: class Unit : Object, class Player : Unit. Each constructor do things like this: Object::Object() { objectType= TYPEMASK_OBJECT; // ... lots of code ... } Item::Item() { objectType |= TYPEMASK_ITEM; // ... } Container::Container(): Item() { objectType |= (TYPEMASK_ITEM | TYPEMASK_CONTAINER); // ... } What is objectType? This field is used when a networksend packet is created. In the packet it is 1 byte of flags, so it is in object hierarchy. So the question was: what type should objectType field have in Haskell? I think it must not mimic enum. What the structure have I to use? There is one more problem - there may be lots of objects, lots of, so memory efficiency is also suggested. And side question: what to do with classes? =) Maybe there is simple rule to convert OO hierarchy to FP. 23 січня 2012 р. 12:15 Malcolm Wallace malcolm.wall...@me.com написав: 2012/1/22 Данило Глинський abcz2.upr...@gmail.com What is natural Haskell representation of such enum? enum TypeMask { UNIT, GAMEOBJECT, CREATURE_OR_GAMEOBJECT = UNIT | GAMEOBJECT }; I don't think that definition makes any sense in C, because UNIT is 0, so UNIT | GAMEOBJECT == GAMEOBJECT == 1 Nevertheless, in Haskell something vaguely similar might be: data TypeMask = UNIT | GAMEOBJECT | CREATURE_OR_GAMEOBJECT // 1-byte flaged enum enum TypeMask { // ... UNIT= 0x0004, GAMEOBJECT = 0x0008, // ... CREATURE_OR_GAMEOBJECT = UNIT | GAMEOBJECT WORLDOBJECT = UNIT | PLAYER | GAMEOBJECT | DYNAMICOBJECT | CORPSE // ... even more enum combos ... }; import Data.Bits data TypeMask = UNIT | GAMEOBJECT | CREATURE_OR_GAMEOBJECT | WORLDOBJECT instance Enum TypeMask where fromEnum UNIT = 0x4 fromEnum GAMEOBJECT = 0x8 fromEnum CREATURE_OR_GAMEOBJECT = fromEnum UNIT .|. fromEnum GAMEOBJECT fromEnum WORLDOBJECT = fromEnum UNIT .|. fromEnum PLAYER .|. fromEnum GAMEOBJECT .|. fromEnum DYNAMICOBJECT .|. fromEnum CORPSE toEnum 0x4 = UNIT toEnum 0x8 = GAMEOBJECT toEnum _ = error unspecified enumeration value of type TypeMask isCreatureOrGameObject :: Int - Bool isCreatureOrGameObject x = (x .|. fromEnum CREATURE_OR_GAMEOBJECT) /= 0 isWorldObject :: Int - Bool isWorldObject x = (x .|. fromEnum WORLDOBJECT) /= 0 -- But fundamentally, this is not an idiomatic Haskell way of doing things. -- The other posts in this thread have shown more Haskell-ish translations. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C][enums][newbie] What is natural Haskell representation of such enum?
On 2012-01-23 13.45.50 -0800, David Barbour wrote: If your classes are more like `interfaces`, you could use Typeclasses to model them. Otherwise, look into OOHaskell. But I think your program architecture will simply be different in idiomatic Haskell than in idiomatic C++. If your OO is very design patterned, and especially if it prefers composition over inheritence, you can port it sorta directly, sometimes. For example, all the classes that implement an interface become a sum type, and their methods are functions that take a value of the sum type. interface MusicCompilation { def trackListing() : [Song] } class Record implements MusicCompilation { ... } class BlogPost implements MusicCompilation { ... } Could translate to data MusicCompilation = Record [Song] | BlogPost [Song] trackListing (Record xs) = xs trackListing (BlogPost xs) = xs The more your OO looks like C, the harder this will be. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C][enums][newbie] What is natural Haskell representation of such enum?
Performing bit-mask operations is possible via the Data.Bits operations (on elements of type Word8 or Word16, etc.). But I must say, it doesn't seem very `natural` in Haskell, nor even in other languages. It crosses lines, binding abstraction to representation in order to improve efficiency. The natural way in Haskell to model model `CREATURE_OR_GAMEOBJECT` would simply be as a function (e.g. of type Object - Bool, or ObjectType - Bool). Regards, Dave 2012/1/22 Данило Глинський abcz2.upr...@gmail.com What is natural Haskell representation of such enum? enum TypeMask { UNIT, GAMEOBJECT, CREATURE_OR_GAMEOBJECT = UNIT | GAMEOBJECT }; More sophisticated question is: and what data structures must be used when converting this naturally one to Haskell? // 1-byte flaged enum enum TypeMask { // ... UNIT= 0x0004, GAMEOBJECT = 0x0008, // ... CREATURE_OR_GAMEOBJECT = UNIT | GAMEOBJECT WORLDOBJECT = UNIT | PLAYER | GAMEOBJECT | DYNAMICOBJECT | CORPSE // ... even more enum combos ... }; ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C][enums][newbie] What is natural Haskell representation of such enum?
Данило Глинський wrote: What is natural Haskell representation of such enum? enum TypeMask { UNIT, GAMEOBJECT, CREATURE_OR_GAMEOBJECT = UNIT | GAMEOBJECT }; data ObjectType = Unit | GameObject creatureOrGameObject :: ObjectType - Bool creatureOrGameObject Unit = True creatureOrGameObject GameObject = True creatureOrGameObject _ = False More sophisticated question is: and what data structures must be used when converting this naturally one to Haskell? // 1-byte flaged enum enum TypeMask { // ... UNIT= 0x0004, GAMEOBJECT = 0x0008, // ... CREATURE_OR_GAMEOBJECT = UNIT | GAMEOBJECT WORLDOBJECT = UNIT | PLAYER | GAMEOBJECT | DYNAMICOBJECT | CORPSE // ... even more enum combos ... }; Pretty much as above, add all the different single bit masks as constructors to ObjectType and define functions for the ones that are a combination of one ore more constructor. Erik -- -- Erik de Castro Lopo http://www.mega-nerd.com/ ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C][enums][newbie] What is natural Haskell representation of such enum?
I may be curious to see how you intend to use such enum... It is very C-wise, I'm not sure it will be very handy, but I need some context. 2012/1/22 Данило Глинський abcz2.upr...@gmail.com What is natural Haskell representation of such enum? enum TypeMask { UNIT, GAMEOBJECT, CREATURE_OR_GAMEOBJECT = UNIT | GAMEOBJECT }; More sophisticated question is: and what data structures must be used when converting this naturally one to Haskell? // 1-byte flaged enum enum TypeMask { // ... UNIT= 0x0004, GAMEOBJECT = 0x0008, // ... CREATURE_OR_GAMEOBJECT = UNIT | GAMEOBJECT WORLDOBJECT = UNIT | PLAYER | GAMEOBJECT | DYNAMICOBJECT | CORPSE // ... even more enum combos ... }; ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C Binding] Turning the mutable to immutable?
On 5 jul 2010, at 23:48, Yves Parès wrote: Hello, I don't know if some of you are familiar with the SFML library (stands for Simple and Fast Multimedia Library) -- http://sfml-dev.org As SDL, SFML is a 2D graphics library, but conversely to SDL it provides a hardware-accelerated drawing, through OpenGL. Well, I'm currently writing its Haskell binding, and I'm stuck with design issues. What I'm heading to is a full IO binding, and that's what I'd like to avoid. Have you considered writing a low-level binding and building a high-level library on top of that? -chris___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C Binding] Turning the mutable to immutable?
That's indeed an advice I've read [1]. But wouldn't it damage the performances, since code will have to go through an extra layer? [1] http://blog.ezyang.com/2010/06/principles-of-ffi-api-design 2010/7/7 Chris Eidhof ch...@eidhof.nl On 5 jul 2010, at 23:48, Yves Parès wrote: Hello, I don't know if some of you are familiar with the SFML library (stands for Simple and Fast Multimedia Library) -- http://sfml-dev.org As SDL, SFML is a 2D graphics library, but conversely to SDL it provides a hardware-accelerated drawing, through OpenGL. Well, I'm currently writing its Haskell binding, and I'm stuck with design issues. What I'm heading to is a full IO binding, and that's what I'd like to avoid. Have you considered writing a low-level binding and building a high-level library on top of that? -chris ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C Binding] Turning the mutable to immutable?
Making an immutable API from a mutable one generally damages performance (on von neumann architectures) somewhat, the goal is to minimize that impact. Cheers. ~Liam On 7 July 2010 19:40, Yves Parès limestr...@gmail.com wrote: That's indeed an advice I've read [1]. But wouldn't it damage the performances, since code will have to go through an extra layer? [1] http://blog.ezyang.com/2010/06/principles-of-ffi-api-design 2010/7/7 Chris Eidhof ch...@eidhof.nl On 5 jul 2010, at 23:48, Yves Parès wrote: Hello, I don't know if some of you are familiar with the SFML library (stands for Simple and Fast Multimedia Library) -- http://sfml-dev.org As SDL, SFML is a 2D graphics library, but conversely to SDL it provides a hardware-accelerated drawing, through OpenGL. Well, I'm currently writing its Haskell binding, and I'm stuck with design issues. What I'm heading to is a full IO binding, and that's what I'd like to avoid. Have you considered writing a low-level binding and building a high-level library on top of that? -chris ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C Binding] Turning the mutable to immutable?
I think it might influence performance, but it doesn't have to be that much. There are some optimization tricks you can apply to deal with this. Premature optimization is the root of all evil ;) -chris On 7 jul 2010, at 11:40, Yves Parès wrote: That's indeed an advice I've read [1]. But wouldn't it damage the performances, since code will have to go through an extra layer? [1] http://blog.ezyang.com/2010/06/principles-of-ffi-api-design 2010/7/7 Chris Eidhof ch...@eidhof.nl On 5 jul 2010, at 23:48, Yves Parès wrote: Hello, I don't know if some of you are familiar with the SFML library (stands for Simple and Fast Multimedia Library) -- http://sfml-dev.org As SDL, SFML is a 2D graphics library, but conversely to SDL it provides a hardware-accelerated drawing, through OpenGL. Well, I'm currently writing its Haskell binding, and I'm stuck with design issues. What I'm heading to is a full IO binding, and that's what I'd like to avoid. Have you considered writing a low-level binding and building a high-level library on top of that? -chris ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C Binding] Turning the mutable to immutable?
2010/7/7 Liam O'Connor lia...@cse.unsw.edu.au Making an immutable API from a mutable one generally damages performance (on von neumann architectures) somewhat, the goal is to minimize that impact. In fact, I would like to determine if an EFFICIENT way to make images and such immutable exists, or if it is impossible. I looked at graphics-drawingcombinators. It is nice, but it doesn't fully answer to my problem since it just loads images and draws them. It provides no ways to alter them, no problem of mutability, then. 2010/7/7 Chris Eidhof ch...@eidhof.nl Premature optimization is the root of all evil ;) Yes, you are right, this is wise. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C Binding] Turning the mutable to immutable?
On Wed, Jul 7, 2010 at 2:24 PM, Yves Parès limestr...@gmail.com wrote: 2010/7/7 Liam O'Connor lia...@cse.unsw.edu.au Making an immutable API from a mutable one generally damages performance (on von neumann architectures) somewhat, the goal is to minimize that impact. In fact, I would like to determine if an EFFICIENT way to make images and such immutable exists, or if it is impossible. Both OpenGL and DirectX, while supporting updates to images, make it slow enough that any image data is effectively immutable. Each animation step a completely fresh frame buffer is created, without overwriting any of the inputs, by combining these immutable images in interesting ways. You're expected to combine multiple immutable data sources in the shader to produce the final output (which will be a different image from the inputs). Examples of data sources would be images, transformation matrices, colours etc. It's extremely rare to see people poke values individually into a mutable buffer (in fact, the capability of doing this on the GPU is very recent, and even then it's highly limited). You do a big purely functional transform from inputs to outputs instead. HLSL and GLSL may not look like functional languages, but they essentially are, in that each kernel runs independently with no shared mutable state, producing outputs from immutable inputs. So, if you want to do it on the CPU, I would mimic the way GPUs have been doing it for ages. Define what operations you want to perform in terms of the inputs, and then do them all in bulk to produce the output image. You don't want people to go in and arbitrarily set pixels to anything they want at any time they want. -- Sebastian Sylvan ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C Binding] Turning the mutable to immutable?
Okay, so I think that the better idea is to carry on with my low-level, imperative binding, and then build a more functional on top of this. Concerning the mutability of images, I notice that the problem with SFML is that it handles Sprites in a way that is even more imperative than OpenGL texture handling. 2010/7/7 Sebastian Sylvan sebastian.syl...@gmail.com On Wed, Jul 7, 2010 at 2:24 PM, Yves Parès limestr...@gmail.com wrote: 2010/7/7 Liam O'Connor lia...@cse.unsw.edu.au Making an immutable API from a mutable one generally damages performance (on von neumann architectures) somewhat, the goal is to minimize that impact. In fact, I would like to determine if an EFFICIENT way to make images and such immutable exists, or if it is impossible. Both OpenGL and DirectX, while supporting updates to images, make it slow enough that any image data is effectively immutable. Each animation step a completely fresh frame buffer is created, without overwriting any of the inputs, by combining these immutable images in interesting ways. You're expected to combine multiple immutable data sources in the shader to produce the final output (which will be a different image from the inputs). Examples of data sources would be images, transformation matrices, colours etc. It's extremely rare to see people poke values individually into a mutable buffer (in fact, the capability of doing this on the GPU is very recent, and even then it's highly limited). You do a big purely functional transform from inputs to outputs instead. HLSL and GLSL may not look like functional languages, but they essentially are, in that each kernel runs independently with no shared mutable state, producing outputs from immutable inputs. So, if you want to do it on the CPU, I would mimic the way GPUs have been doing it for ages. Define what operations you want to perform in terms of the inputs, and then do them all in bulk to produce the output image. You don't want people to go in and arbitrarily set pixels to anything they want at any time they want. -- Sebastian Sylvan ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C Binding] Turning the mutable to immutable?
To answer the question in your subject, “Very Carefully.” While I don’t know much about your particular problem domain (and it seems others have given useful advice), I can say some general things about making mutable things immutable. There is a very simple way to make something mutable immutable: say that you won’t ever mutate it again! Doing this correctly is two-fold: you first have to know when you can do this and when it is useful (which requires in-depth understanding of the side-effects that the low-level API invokes), and second is knowing how to encapsulate your interface so that there is no type-checking use-case of your code (without unsafePerformIO) that accidentally mutates a pure structure. You can use this to do a standard pattern seen in ST and others: mutate during creation inside a monad, but when the monad is done running, return a pure version of the output with unsafePerformIO. If you can guarantee that another caching the pointer so that if someone else calls your function with the same arguments, you return the same pointer, is safe, then this is ok. Memcopying a datastructure when you need to modify it, while a cringe-worthy offense in your theoretical CS class, is a surprisingly practical and not-to-bad performing technique for making your data persistent. It works better the smaller the data structure is, and you'd be surprised how many C libraries implement some feature with a memory copy (moving GC, anyone?) Cheers, Edward ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] [C Binding] Turning the mutable to immutable?
On 07/05/2010 04:48 PM, Yves Parès wrote: 3) Is there another library on hackage that handles images in a functional way? (I mean not /all in IO/) Check out graphics-drawingcombinators. - Jake ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C variable access via FFI
On Tue, Apr 20, 2010 at 8:48 AM, Tom Hawkins tomahawk...@gmail.com wrote: I have a bunch of global variables in C I would like to directly read and write from Haskell. Is this possible with FFI, or must I write a bunch of C wrapper functions for the interface, i.e. a 'get' and a 'set' for each variable? I believe Maurício C. Antunes' bindings-DSL has support for automating reading from and writing to global variables. Look at the Detailed usage guide from the home page of: http://hackage.haskell.org/package/bindings-DSL regards, Bas ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C variable access via FFI
Tom Hawkins wrote: I have a bunch of global variables in C I would like to directly read and write from Haskell. Is this possible with FFI, Yes it is, as explained in section 4.1.1. in the FFI specification [1]. An import for a global variable int bar would look like this: foreign import ccall bar bar :: Ptr CInt The difference to an import of a function int foo() is the extra . HTH, Bertram [1] http://www.cse.unsw.edu.au/~chak/haskell/ffi/ffi/ffise4.html#x7-170004.1.1 ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C variable access via FFI
On Tue, Apr 20, 2010 at 01:48:16AM -0500, Tom Hawkins wrote: I have a bunch of global variables in C I would like to directly read and write from Haskell. Is this possible with FFI, or must I write a bunch of C wrapper functions for the interface, i.e. a 'get' and a 'set' for each variable? Yup. foo.c: int my_int; Foo.hs: foreign import my_int my_int_ptr :: Ptr Int foo = do poke my_int_ptr 4 x - peek my_int_Ptr John -- John Meacham - ⑆repetae.net⑆john⑈ - http://notanumber.net/ ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C functional programming techniques?
2010/1/29 Maurício CA: Sorry if this looks weird, but do you know of experiences with functional programming, or type programming, with C? Using macro tricks or just good specifications? This is probably not what you're looking for, but it's related: Single-Assignment C (Functional Array Programming for High-Performance Computing) http://www.sac-home.org/ From the website: SaC is an array programming language predominantly suited for application areas such as numerically intensive applications and signal processing. Its distinctive feature is that it combines high-level program specifications with runtime efficiency similar to that of hand-optimized low-level specifications. Key to the optimization process that facilitates these runtimes is the underlying functional model which also constitutes the basis for implicit parallelization. This makes SaC ideally suited for utilizing the full potential of modern CMP architectures such as multi-cores or the Cell processor. Regards, Sean ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C functional programming techniques?
On Jan 29, 2010, at 9:11 AM, Maurí cio CA wrote: Sorry if this looks weird, but do you know of experiences with functional programming, or type programming, with C? Using macro tricks or just good specifications? I know this is not absurd to a small extent. I've heard of proof tool certificated C code on the net (although I don't understand that theory), and I was also able to use what I learned from Haskell in a few C-like tasks. [*] I would use a higher level language to emit valid C. Basically, use a strongly typed macro language. All you will have to prove is that your emitter produces type safe code, which you can do by induction and is straight forward. You can build up a small library of combinators for type safe units of C code. Haskell might be a good choice for writing your C pre-processor, but there are plenty of choices. Using something like ehaskell (or eruby) might be a good approach. http://hackage.haskell.org/package/ehaskell ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C functional programming techniques?
Maurício CA wrote: Hi, all, Sorry if this looks weird, but do you know of experiences with functional programming, or type programming, with C? Using macro tricks or just good specifications? I know there is some type level programming (not strictly functional) in CCAN: http://ccan.ozlabs.org/ Not sure if this is what you're after though. Erik -- -- Erik de Castro Lopo http://www.mega-nerd.com/ ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C headers in cabal dependencies
On Wed, 2009-10-28 at 17:34 -0200, Maurício CA wrote: Hi, I've been using 'install-includes' in a package. I sometimes make small changes to those include files, and I've seen that cabal doesn't consider then dependencies, i.e., doesn't rebuild .hsc files depending on then. I'm not sure if this is an error, as parsing hsc2hs input may not be cabal task. Anyway, I would like to suggest that files in install-includes be considered dependencies and that files under 'includes' be also included when processing '.hsc' files. This is an instance of the long standing lack of module/file dependency tracking in Cabal: http://hackage.haskell.org/trac/hackage/ticket/15 Duncan ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C structures
I need anyones experience. Possibly this old post of mine can help: http://therning.org/magnus/archives/315 Oh... WHile i was trying to repeat after you, it's become clear to me that this is not actually what I want. I want to create some structure, say data WM = WM {some_info :: Ptr CChar} create pointer for it type LPWM = Ptr WM and, when i need to convert it to something Int (or UINT) I found in Graphics.Win32 function castPtrToUINT :: Ptr a - UINT So my question now is: would the structure defined in haskell as written in http://therning.org/magnus/archives/315, which pointer i will send to another C-function? be restored properly? Or maybe there's another function? which allows to do so? ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C structures
On 13/11/09 05:31, Vasiliy G. Stavenko wrote: Hello everyone. What about passing complex c-types (structures) to c-functions. More detailed: I have an application in production which was written in Delphi. IT has ability to create pluggable modules to it. Interface realized by sending Win32Api messages to application. function in haskell Win32 Graphics.Win32.sendMessage :: HWND - WyidowMessage- WPARAM - LPARAM - IO RESULT Application wants to get different data in WPARAM and LPARAM. Such as window descriptor (HWND), string pointers and datastructer pointers. The latter i don't know how to create. I need anyones experience. Possibly this old post of mine can help: http://therning.org/magnus/archives/315 /M -- Magnus Therning(OpenPGP: 0xAB4DFBA4) magnus@therning.org Jabber: magnus@therning.org http://therning.org/magnus identi.ca|twitter: magthe signature.asc Description: OpenPGP digital signature ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C-like Haskell
On Wed, Jan 28, 2009 at 04:42:49PM -0800, drblanco wrote: Here's my attempt, which takes about 75s for r=10^8. circ2 r = (1+4*r) + 4 * (circ2' (rs+1) r 1 0) where rs = r^2 circ2' rad x y sum | xy = sum | rad=rs = circ2' (rad+1+2*y) x (y+1) (sum+1+2*(x-y)) | otherwise = circ2' (rad+1-2*x) (x-1) y sum For comparison, the C code below runs in 1 second. typedef unsigned long long bigint; bigint gausscount(bigint r) { bigint sum=0; bigint x, y; bigint rs=r*r; bigint rad=rs+1; x=r; y=1; while (yx) { while (radrs) { rad-=2*x; rad++; x--; } sum+=1+2*(x-y); rad+=2*y+1; y++; } sum*=4; sum++; return sum; } for the curious, here is the C output of jhc when fed circ2 annotated with the obvious bang-patterns (the strictness analyzer still needs some help): other than giving every intermediate value a name, and only performing one operation a line (which doesn't bother gcc at all), it is pretty darn close to the hand optimized C code... variable guide: x - v86 y - v88 rs - v4146 rad - v84 and sum is accumulated in v90 static uint64_t circ2(uint64_t v12) { uint64_t v212; uint64_t v4146 = (v12 * v12); uint64_t v4758 = (4 * v12); uint64_t v4786 = (1 + v4758); uint64_t v4160 = (1 + v4146); uint64_t v84 = v4160; uint64_t v86 = v12; uint64_t v88 = 1; uint64_t v90 = 0; fW_a__fMain__3_ucirc2_t_u2:; { uint16_t v10 = (((int64_t)v86) ((int64_t)v88)); if (0 == v10) { uint16_t v12 = (((int64_t)v84) = ((int64_t)v4146)); if (0 == v12) { uint64_t v4338 = (1 + v84); uint64_t v4352 = (2 * v86); uint64_t v4366 = (v4338 - v4352); uint64_t v4380 = (v86 - 1); v84 = v4366; v86 = v4380; v88 = v88; v90 = v90; goto fW_a__fMain__3_ucirc2_t_u2; } else { /* 1 */ uint64_t v4226 = (1 + v90); uint64_t v4772 = (v86 - v88); uint64_t v4282 = (2 * v4772); uint64_t v4296 = (v4226 + v4282); uint64_t v4310 = (1 + v88); uint64_t v4240 = (1 + v84); uint64_t v4254 = (2 * v88); uint64_t v4324 = (v4240 + v4254); v84 = v4324; v86 = v86; v88 = v4310; v90 = v4296; goto fW_a__fMain__3_ucirc2_t_u2; } } else { /* 1 */ v212 = v90; } } uint64_t v4174 = (4 * v212); return v4786 + v4174; } John -- John Meacham - ⑆repetae.net⑆john⑈ ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C-like Haskell
I had a quick look at the code for loop :: Int64 - Int64 - Int64 loop i r = if i == 0 then r else loop (i-1) (r+1) It's quite bad. It's full of C calls. It would be much better to do what gcc does and treat Int64 as a primitive type, and just insert C calls for the tricky operations, like division. On Thu, Jan 29, 2009 at 3:17 AM, Duncan Coutts duncan.cou...@worc.ox.ac.uk wrote: On Wed, 2009-01-28 at 20:42 -0500, Ross Mellgren wrote: Very possibly -- I'm on a mac so no prebuilt 64-bit binary. I'm not good enough at reading core to tell, but I can tell from the core that it's calling out to external C functions to do the 64-bit math. Right, that'll make it really slow but does not explain the allocations. It could be that it's crossing over from machine register size to managed heap object and so without additional help on 32-bit it wants to allocate thunks. If it's using Int64 then there's no transition, that only happens with Integer (which is always heap allocated anyway). The sum parameter in the inner loop is an accumulating parameter that is not inspected until the final value is returned. In the case of the simple direct Int64 implementation the strictness analyser does notice that it really is strict so can be evaluated as we go along. I bet that's the source of the problem, that for the indirect Int64 impl used on 32bit machines the strictness analyser does not discover the same property. So that would explain the allocations. It's worth investigating the indirect Int64 implementation to see if this could be improved. Does your core indicate that it's making a bunch of external __ccalls? No, it's all unboxed Int# types and primitive # operations. Lovely. In particular the inner loop is all unboxed types with no allocations. Duncan ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C-like Haskell
On Wed, 2009-01-28 at 16:42 -0800, drblanco wrote: I do already have the number I wanted, but was wondering how this could be made faster, or even why it's so slow. This is all on GHC 6.8.3 under OS X Intel, using ghc -O2. I'm not exactly sure what's different, but for me it works pretty well. I put back in the Int64 type signature. For comparison, the C code below runs in 1 second. You've got a faster machine than me :-) I compiled both the Haskell and C versions to standalone executables with ghc/gcc -O2 and ran them with time. C version: $ time ./circ 3141592649589764829 real0m2.430s user0m2.428s sys 0m0.000s Haskell version: time ./circ2 3141592653589764829 real0m2.753s user0m2.756s sys 0m0.000s Not too bad I'd say! :-) I was using ghc-6.10 for this test. It would appear that ghc-6.8 is a bit slower, I get: 3141592653589764829 real0m5.767s user0m5.768s sys 0m0.000s Now the other difference is that I'm using a 64bit machine so perhaps ghc just produces terrible code for Int64 on 32bit machines. Duncan ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C-like Haskell
Did you print it? I'm using same code with ghc --make -O2 and it takes forever to finish. On Wed, Jan 28, 2009 at 8:06 PM, Duncan Coutts duncan.cou...@worc.ox.ac.uk wrote: On Wed, 2009-01-28 at 16:42 -0800, drblanco wrote: I do already have the number I wanted, but was wondering how this could be made faster, or even why it's so slow. This is all on GHC 6.8.3 under OS X Intel, using ghc -O2. I'm not exactly sure what's different, but for me it works pretty well. I put back in the Int64 type signature. For comparison, the C code below runs in 1 second. You've got a faster machine than me :-) I compiled both the Haskell and C versions to standalone executables with ghc/gcc -O2 and ran them with time. C version: $ time ./circ 3141592649589764829 real0m2.430s user0m2.428s sys 0m0.000s Haskell version: time ./circ2 3141592653589764829 real0m2.753s user0m2.756s sys 0m0.000s Not too bad I'd say! :-) I was using ghc-6.10 for this test. It would appear that ghc-6.8 is a bit slower, I get: 3141592653589764829 real0m5.767s user0m5.768s sys 0m0.000s Now the other difference is that I'm using a 64bit machine so perhaps ghc just produces terrible code for Int64 on 32bit machines. Duncan ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C-like Haskell
On Wed, 2009-01-28 at 20:11 -0500, sam lee wrote: Did you print it? I'm using same code with ghc --make -O2 and it takes forever to finish. Yes, you can see in the output that it prints the same answer in each case. I was using r = 10^9 as you suggested. C version: $ time ./circ 3141592649589764829 Haskell version: time ./circ2 3141592653589764829 Duncan ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C-like Haskell
Duncan, I think you must have some magics -- on my machine the original code also takes forever. Running with +RTS -S indicates it's allocating several gig of memory or more. Applying some bang patterns gives me ~8s for 10^8 and somewhat more than a minute for 10^9: {-# LANGUAGE BangPatterns #-} module Main where import Data.Int main = putStrLn $ show $ circ2 (10^8) circ2 :: Int64 - Int64 circ2 r = ((1+4*r) + 4 * (go (rs+1) r 1 0)) where rs = r^2 go :: Int64 - Int64 - Int64 - Int64 - Int64 go !rad !x !y !sum | x y = sum | rad = rs = go (rad+1+2*y) x (y+1) (sum+1+2*(x-y)) | otherwise = go (rad+1-2*x) (x-1) y sum 10^8: r...@hugo:~$ time ./circ-bangpatterns +RTS -t ./circ-bangpatterns +RTS -t 31415926535867961 ghc: 9120 bytes, 1 GCs, 2432/2432 avg/max bytes residency (1 samples), 1M in use, 0.00 INIT (0.00 elapsed), 8.15 MUT (8.31 elapsed), 0.00 GC (0.00 elapsed) :ghc real0m8.315s user0m8.154s sys 0m0.050s 10^9: r...@hugo:~$ time ./circ-bangpatterns +RTS -t ./circ-bangpatterns +RTS -t 3141592653589764829 ghc: 9336 bytes, 1 GCs, 2432/2432 avg/max bytes residency (1 samples), 1M in use, 0.00 INIT (0.00 elapsed), 80.49 MUT (82.68 elapsed), 0.00 GC (0.00 elapsed) :ghc real1m22.684s user1m20.490s sys 0m0.473s The C program is quite fast: r...@hugo:~$ time ./circ-orig 1302219321 real0m1.073s user0m1.039s sys 0m0.006s -Ross On Jan 28, 2009, at 8:06 PM, Duncan Coutts wrote: On Wed, 2009-01-28 at 16:42 -0800, drblanco wrote: I do already have the number I wanted, but was wondering how this could be made faster, or even why it's so slow. This is all on GHC 6.8.3 under OS X Intel, using ghc -O2. I'm not exactly sure what's different, but for me it works pretty well. I put back in the Int64 type signature. For comparison, the C code below runs in 1 second. You've got a faster machine than me :-) I compiled both the Haskell and C versions to standalone executables with ghc/gcc -O2 and ran them with time. C version: $ time ./circ 3141592649589764829 real0m2.430s user0m2.428s sys 0m0.000s Haskell version: time ./circ2 3141592653589764829 real0m2.753s user0m2.756s sys 0m0.000s Not too bad I'd say! :-) I was using ghc-6.10 for this test. It would appear that ghc-6.8 is a bit slower, I get: 3141592653589764829 real0m5.767s user0m5.768s sys 0m0.000s Now the other difference is that I'm using a 64bit machine so perhaps ghc just produces terrible code for Int64 on 32bit machines. Duncan ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C-like Haskell
On Wed, 2009-01-28 at 20:23 -0500, Ross Mellgren wrote: Duncan, I think you must have some magics -- on my machine the original code also takes forever. Running with +RTS -S indicates it's allocating several gig of memory or more. It runs in a tiny heap for me: ./circ2 +RTS -A10k -M20k -RTS 3141592653589764829 +RTS -S indicates it allocated 8,512 bytes. Applying some bang patterns gives me ~8s for 10^8 and somewhat more than a minute for 10^9: I wonder if it is the 64 vs 32 bit machine difference. I recall some ghc ticket about Int64 having rather poor performance on 32bit x86 machines. I don't have a 32bit x86 machine to hand so I cannot easily test it. Duncan ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C-like Haskell
Thanks for the help. It's clear in retrospect that it was being too lazy, but not why changing to Int64 did it. The bang patterns made the difference between runnable and not. GHC 6.10 didn't make much of a difference, but there's no 64-bit build for the Mac. If this seems to come up again I'll have to set up 64-bit Linux in a virtual machine, which seems a bit convoluted. David On Wed, Jan 28, 2009 at 7:37 PM, Duncan Coutts duncan.cou...@worc.ox.ac.uk wrote: On Wed, 2009-01-28 at 20:23 -0500, Ross Mellgren wrote: Duncan, I think you must have some magics -- on my machine the original code also takes forever. Running with +RTS -S indicates it's allocating several gig of memory or more. It runs in a tiny heap for me: ./circ2 +RTS -A10k -M20k -RTS 3141592653589764829 +RTS -S indicates it allocated 8,512 bytes. Applying some bang patterns gives me ~8s for 10^8 and somewhat more than a minute for 10^9: I wonder if it is the 64 vs 32 bit machine difference. I recall some ghc ticket about Int64 having rather poor performance on 32bit x86 machines. I don't have a 32bit x86 machine to hand so I cannot easily test it. Duncan ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C-like Haskell
Ross Mellgren wrote: Duncan, I think you must have some magics -- on my machine the original code also takes forever. Running with +RTS -S indicates it's allocating several gig of memory or more. Applying some bang patterns gives me ~8s for 10^8 and somewhat more than a minute for 10^9 It works great for me. 64 bit, GHC 6.10.1, no bang patterns or other magic. Works about the same with both Int and Int64. % time ./ctest 3141592649589764829 real0m2.614s user0m2.610s sys 0m0.003s % time ./hstest 3141592653589764829 real0m3.878s user0m3.870s sys 0m0.003s % ./hstest +RTS -S ./hstest +RTS -S AllocCopied LiveGCGC TOT TOT Page Flts bytes bytes bytes user elapuserelap 3141592653589764829 8512 688 17136 0.00 0.003.943.9400 (Gen: 1) 0 0.00 0.00 8,512 bytes allocated in the heap 688 bytes copied during GC 17,136 bytes maximum residency (1 sample(s)) 19,728 bytes maximum slop 1 MB total memory in use (0 MB lost due to fragmentation) Generation 0: 0 collections, 0 parallel, 0.00s, 0.00s elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed INIT time0.00s ( 0.00s elapsed) MUT time3.94s ( 3.94s elapsed) GCtime0.00s ( 0.00s elapsed) EXIT time0.00s ( 0.00s elapsed) Total time3.94s ( 3.94s elapsed) %GC time 0.0% (0.0% elapsed) Alloc rate2,158 bytes per MUT second Productivity 99.9% of total user, 100.0% of total elapsed ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C-like Haskell
Apparently 64-bit GHC is sufficiently advanced to be indistinguishable from magic. Now, if only there was a 64-bit binary for Mac OS X :-/ -Ross On Jan 28, 2009, at 9:06 PM, Jake McArthur wrote: Ross Mellgren wrote: Duncan, I think you must have some magics -- on my machine the original code also takes forever. Running with +RTS -S indicates it's allocating several gig of memory or more. Applying some bang patterns gives me ~8s for 10^8 and somewhat more than a minute for 10^9 It works great for me. 64 bit, GHC 6.10.1, no bang patterns or other magic. Works about the same with both Int and Int64. % time ./ctest 3141592649589764829 real0m2.614s user0m2.610s sys 0m0.003s % time ./hstest 3141592653589764829 real0m3.878s user0m3.870s sys 0m0.003s % ./hstest +RTS -S ./hstest +RTS -S AllocCopied LiveGCGC TOT TOT Page Flts bytes bytes bytes user elapuserelap 3141592653589764829 8512 688 17136 0.00 0.003.943.9400 (Gen: 1) 0 0.00 0.00 8,512 bytes allocated in the heap 688 bytes copied during GC 17,136 bytes maximum residency (1 sample(s)) 19,728 bytes maximum slop 1 MB total memory in use (0 MB lost due to fragmentation) Generation 0: 0 collections, 0 parallel, 0.00s, 0.00s elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed INIT time0.00s ( 0.00s elapsed) MUT time3.94s ( 3.94s elapsed) GCtime0.00s ( 0.00s elapsed) EXIT time0.00s ( 0.00s elapsed) Total time3.94s ( 3.94s elapsed) %GC time 0.0% (0.0% elapsed) Alloc rate2,158 bytes per MUT second Productivity 99.9% of total user, 100.0% of total elapsed ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C-like Haskell
On Wed, 2009-01-28 at 20:42 -0500, Ross Mellgren wrote: Very possibly -- I'm on a mac so no prebuilt 64-bit binary. I'm not good enough at reading core to tell, but I can tell from the core that it's calling out to external C functions to do the 64-bit math. Right, that'll make it really slow but does not explain the allocations. It could be that it's crossing over from machine register size to managed heap object and so without additional help on 32-bit it wants to allocate thunks. If it's using Int64 then there's no transition, that only happens with Integer (which is always heap allocated anyway). The sum parameter in the inner loop is an accumulating parameter that is not inspected until the final value is returned. In the case of the simple direct Int64 implementation the strictness analyser does notice that it really is strict so can be evaluated as we go along. I bet that's the source of the problem, that for the indirect Int64 impl used on 32bit machines the strictness analyser does not discover the same property. So that would explain the allocations. It's worth investigating the indirect Int64 implementation to see if this could be improved. Does your core indicate that it's making a bunch of external __ccalls? No, it's all unboxed Int# types and primitive # operations. Lovely. In particular the inner loop is all unboxed types with no allocations. Duncan ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ interface with Haskell
Evan Laforge wrote: To threadjack a little bit, I've been interfacing haskell with c++. It gets awkward when the c++ structures use STL types like string and vector. Of course those are too complex for haskell to marshal to. What I've been doing is defining an XMarshal variant of the X c++ class, that uses plain c arrays. Then I marshal to that, and construct the c++ object properly from XMarshal in the c-c++ wrapper layer. On a few occasions, when the c++ class is really big and only has one STL member, I make a partially constructed c++ object, pass the array separately, and then construct the proper c++ class from the broken haskell generated one. Possibly dangerous as all get-out because I'm dealing with unconstructed c++ objects, but it seems to work. you mean, you hack around with the internal representation of those structures? Well, if you want to avoid double-copying, C++ can't access Haskell sequences, and Haskell can't access C++ sequences, I guess I don't see an alternative. Passing back to haskell is easier since I can use *vec.begin(), which according to the internet should be safe because STL guarantees that vector contents are contiguous. safe until either: the vector's contents change, if Haskell is assuming it's immutable, or more seriously, if the vector's length is changed, the pointers are invalidated and it might crash (due to reallocating for a bigger continuous memory chunk) I'm only saved by the fact that I don't have that many different kinds of classes to pass. This would be much more drudgery if I had more. Does anyone have a better solution or convention for marshalling c++ objects? not better, but, you could wrap the methods of the class and call back into C++ (through C wrappers) to do anything with the class, if it suited your purposes better and wasn't too slow I've also noticed warnings from g++ about hsc2hs's use of the OFFSETOF macro on c++ classes, but some googling of g++ mailing lists implied that it's harmless if you don't have virtual bases, and what sane person does, so I suppress it now :) ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ interface with Haskell
you mean, you hack around with the internal representation of those structures? Well, if you want to avoid double-copying, C++ can't access Haskell sequences, and Haskell can't access C++ sequences, I guess I don't see an alternative. I don't really mind double copying, but having to declare c variants (i.e. no stl) of all the c++ structures and then copy from one to the other is a little tedious. I was hoping there was some clever trick to make that easier... Passing back to haskell is easier since I can use *vec.begin(), which according to the internet should be safe because STL guarantees that vector contents are contiguous. safe until either: the vector's contents change, if Haskell is assuming it's immutable, Well, naturally I peekArray before letting c++ have it back. I'm only saved by the fact that I don't have that many different kinds of classes to pass. This would be much more drudgery if I had more. Does anyone have a better solution or convention for marshalling c++ objects? not better, but, you could wrap the methods of the class and call back into C++ (through C wrappers) to do anything with the class, if it suited your purposes better and wasn't too slow Yeah, I was thinking of that, but it seemed like even more of a hassle. However, a more practical variant might be to write a haskell interface to marshal to vectors and strings, probably involving some void pointer sketchiness since naturally template types can't be expressed in a C function signature, and then poke those into the struct when I pass it. That would only work for vectors stored by pointer of course. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ interface with Haskell
you could write a C++ function to marshal a Sequence (or any Container IIRC, maybe Forward Container) to a vector (or whatever you wanted -- there are choices), and then okay let's see if I remember C++ well enough This design has extra copying. but anyway templatetypename Container std::vectortypename Container::value_type container_to_vector(Container const c) { return std::vectortypename Container::value_type(c.begin(), c.end()); } and templatetypename Container Container vector_to_sequence(std::vectortypename Container::value_type const c) { return Container(c.begin(), c.end()); } extern C { /* the temporary returned variable doesn't last long enough here */ (char*, int)/*I know C++ doesn't have this syntax of tuples*/ string_to_array(std::string const s) { return (*container_to_vector(s).begin()) } } In other words I suspect that it's possible with a minimum of boilerplate per type, (possibly including the use of macros), but I'm not sure exactly what you need to do, and I got tired of being a C++-fu expert a few years ago ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ interface with Haskell
Although you could use gcc to link the code I wouldn't recommend it (mainly for the problems you are currently having) SImply call GHC to compile both the C and Haskell code. It will take care of finding the headers and supplying the necessary linker arguments. ghc -ffi -c foo.hs myfoo_c.c BTW, you don't need to compile viaC 2008/4/17 Miguel Lordelo [EMAIL PROTECTED]: Well Isaac...I became now a little bit smarter then yesterday!!! I show you the example that I found and on which I´m working with. File: foo.hs module Foo where foreign export ccall foo :: Int - IO Int foo :: Int - IO Int foo n = return (length (f n)) f :: Int - [Int] f 0 = [] f n = n:(f (n-1)) To get the C wrapper you insert the following command: ghc -ffi -fvia-C -C foo.hs After execution you will have these following additional files: foo.hc foo.hi foo_stub.c foo_stub.h foo_stub.o What I did next was to create a file named: myfoo_c.c, where I will call the foo function (implemented in Haskell). (you can see this example on http://www.haskell.org/ghc/docs/latest/html/users_guide/ffi-ghc.html ) But the problem is to compile with gcc (must I put any flag or whatever set something) The gcc output is: myfoo_c.c:2:19: error: HsFFI.h: No such file or directory I downloaded this header file from: (I know that is not the correct way, but it was the only idea that occurs at the moment) http://www.koders.com/c/fidD0593B84C41CA71319BB079EFD0A2C80211C9337.aspx I compiled again and the following return error appears: myfoo_c.c:(.text+0x1c): undefined reference to `hs_init' myfoo_c.c:(.text+0x31): undefined reference to `foo' myfoo_c.c:(.text+0x50): undefined reference to `hs_exit' collect2: ld returned 1 exit status These functions are necessary to setup GHC runtime (see: http://www.haskell.org/ghc/docs/latest/html/users_guide/ffi-ghc.html ) What I want to know is how to compile myfoo_c.c?! Is it with GCC or GHC?! Chears, Miguel Lordelo. On Wed, Apr 16, 2008 at 9:16 PM, Isaac Dupree [EMAIL PROTECTED] wrote: perhaps haskell: foreign export foo_func foo :: Int - IO Int -- I forget the rest of the syntax here C++: extern C { int foo_func(int i); } int some_cplusplus_function() { int bat = 3; int blah = foo_func(bat); return blah; } Is that all you need to do? Miguel Lordelo wrote: Hi all, Well...somehow I'm a beginner in Haskell. But actually my interest in Haskell will increase if it is possible to call a haskell function in C++. Something like GreenCard ( http://www.haskell.org/greencard/ ) simplifying the task of interfacing Haskell programs to external libraries (usually). But is there also a task to interface a foreign language with Haskell, but calling Haskell functions. Or c2hs which is an interface generator that simplifies the development of Haskell bindings to C libraries. I want to know this, because in my company some guys are doing some testing with Frotran and MatLab and I want to show them the power of haskell and the software which we are using is implemented in C++ (there is the reason to make Haskel - C++). I read somewhere that the only way for C++ calling a haskell function is to create a binding between Haskell and C and from C to C++, but a easy Hello World example was not there. Unfortunatelly I couldn't found anything usefull, like an complete example, or how to compile the code from haskell to C to C++. Can sombody help me, please :P Chears, Miguel Lordelo. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ interface with Haskell
Thanks, I found on one site how to compile after creating the stub files with GHC: First step: *ghc -c -ffi haskell_file.hs* Second step - here it is important to know and write where are the ghc libraries: *gcc -I /usr/local/lib/ghc-5.04.3/include -c C_file.c * After that it is important to link my creted C_file with the stub file and compile it: *ghc -no-hs-main -o C_file C_file.o haskell_file.o haskell_file_stub.o* The final result is C_file execution file...just enter C_file and the program is running correctly. This information: how to compile and to link C with Haskell and to call a Haskell funtion from C was quite difficult. But here is my result of googling throw the internet and to find something usefull. Next challange: link C++ with C and creating a usefull documentation and put it online! Ciao, Miguel Lordelo. On Fri, Apr 18, 2008 at 3:33 PM, Alfonso Acosta [EMAIL PROTECTED] wrote: Although you could use gcc to link the code I wouldn't recommend it (mainly for the problems you are currently having) SImply call GHC to compile both the C and Haskell code. It will take care of finding the headers and supplying the necessary linker arguments. ghc -ffi -c foo.hs myfoo_c.c BTW, you don't need to compile viaC 2008/4/17 Miguel Lordelo [EMAIL PROTECTED]: Well Isaac...I became now a little bit smarter then yesterday!!! I show you the example that I found and on which I´m working with. File: foo.hs module Foo where foreign export ccall foo :: Int - IO Int foo :: Int - IO Int foo n = return (length (f n)) f :: Int - [Int] f 0 = [] f n = n:(f (n-1)) To get the C wrapper you insert the following command: ghc -ffi -fvia-C -C foo.hs After execution you will have these following additional files: foo.hc foo.hi foo_stub.c foo_stub.h foo_stub.o What I did next was to create a file named: myfoo_c.c, where I will call the foo function (implemented in Haskell). (you can see this example on http://www.haskell.org/ghc/docs/latest/html/users_guide/ffi-ghc.html ) But the problem is to compile with gcc (must I put any flag or whatever set something) The gcc output is: myfoo_c.c:2:19: error: HsFFI.h: No such file or directory I downloaded this header file from: (I know that is not the correct way, but it was the only idea that occurs at the moment) http://www.koders.com/c/fidD0593B84C41CA71319BB079EFD0A2C80211C9337.aspx I compiled again and the following return error appears: myfoo_c.c:(.text+0x1c): undefined reference to `hs_init' myfoo_c.c:(.text+0x31): undefined reference to `foo' myfoo_c.c:(.text+0x50): undefined reference to `hs_exit' collect2: ld returned 1 exit status These functions are necessary to setup GHC runtime (see: http://www.haskell.org/ghc/docs/latest/html/users_guide/ffi-ghc.html ) What I want to know is how to compile myfoo_c.c?! Is it with GCC or GHC?! Chears, Miguel Lordelo. On Wed, Apr 16, 2008 at 9:16 PM, Isaac Dupree [EMAIL PROTECTED] wrote: perhaps haskell: foreign export foo_func foo :: Int - IO Int -- I forget the rest of the syntax here C++: extern C { int foo_func(int i); } int some_cplusplus_function() { int bat = 3; int blah = foo_func(bat); return blah; } Is that all you need to do? Miguel Lordelo wrote: Hi all, Well...somehow I'm a beginner in Haskell. But actually my interest in Haskell will increase if it is possible to call a haskell function in C++. Something like GreenCard ( http://www.haskell.org/greencard/ ) simplifying the task of interfacing Haskell programs to external libraries (usually). But is there also a task to interface a foreign language with Haskell, but calling Haskell functions. Or c2hs which is an interface generator that simplifies the development of Haskell bindings to C libraries. I want to know this, because in my company some guys are doing some testing with Frotran and MatLab and I want to show them the power of haskell and the software which we are using is implemented in C++ (there is the reason to make Haskel - C++). I read somewhere that the only way for C++ calling a haskell function is to create a binding between Haskell and C and from C to C++, but a easy Hello World example was not there. Unfortunatelly I couldn't found anything usefull, like an complete example, or how to compile the code from haskell to C to C++. Can sombody help me, please :P Chears, Miguel Lordelo. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ interface with Haskell
if you'd normally be linking using g++, you'll need (IIRC) -lstdc++ added to linking-ghc's command line Alfonso Acosta wrote: Although you could use gcc to link the code I wouldn't recommend it (mainly for the problems you are currently having) SImply call GHC to compile both the C and Haskell code. It will take care of finding the headers and supplying the necessary linker arguments. ghc -ffi -c foo.hs myfoo_c.c BTW, you don't need to compile viaC 2008/4/17 Miguel Lordelo [EMAIL PROTECTED]: Well Isaac...I became now a little bit smarter then yesterday!!! I show you the example that I found and on which I´m working with. File: foo.hs module Foo where foreign export ccall foo :: Int - IO Int foo :: Int - IO Int foo n = return (length (f n)) f :: Int - [Int] f 0 = [] f n = n:(f (n-1)) To get the C wrapper you insert the following command: ghc -ffi -fvia-C -C foo.hs After execution you will have these following additional files: foo.hc foo.hi foo_stub.c foo_stub.h foo_stub.o What I did next was to create a file named: myfoo_c.c, where I will call the foo function (implemented in Haskell). (you can see this example on http://www.haskell.org/ghc/docs/latest/html/users_guide/ffi-ghc.html ) But the problem is to compile with gcc (must I put any flag or whatever set something) The gcc output is: myfoo_c.c:2:19: error: HsFFI.h: No such file or directory I downloaded this header file from: (I know that is not the correct way, but it was the only idea that occurs at the moment) http://www.koders.com/c/fidD0593B84C41CA71319BB079EFD0A2C80211C9337.aspx I compiled again and the following return error appears: myfoo_c.c:(.text+0x1c): undefined reference to `hs_init' myfoo_c.c:(.text+0x31): undefined reference to `foo' myfoo_c.c:(.text+0x50): undefined reference to `hs_exit' collect2: ld returned 1 exit status These functions are necessary to setup GHC runtime (see: http://www.haskell.org/ghc/docs/latest/html/users_guide/ffi-ghc.html ) What I want to know is how to compile myfoo_c.c?! Is it with GCC or GHC?! Chears, Miguel Lordelo. On Wed, Apr 16, 2008 at 9:16 PM, Isaac Dupree [EMAIL PROTECTED] wrote: perhaps haskell: foreign export foo_func foo :: Int - IO Int -- I forget the rest of the syntax here C++: extern C { int foo_func(int i); } int some_cplusplus_function() { int bat = 3; int blah = foo_func(bat); return blah; } Is that all you need to do? Miguel Lordelo wrote: Hi all, Well...somehow I'm a beginner in Haskell. But actually my interest in Haskell will increase if it is possible to call a haskell function in C++. Something like GreenCard ( http://www.haskell.org/greencard/ ) simplifying the task of interfacing Haskell programs to external libraries (usually). But is there also a task to interface a foreign language with Haskell, but calling Haskell functions. Or c2hs which is an interface generator that simplifies the development of Haskell bindings to C libraries. I want to know this, because in my company some guys are doing some testing with Frotran and MatLab and I want to show them the power of haskell and the software which we are using is implemented in C++ (there is the reason to make Haskel - C++). I read somewhere that the only way for C++ calling a haskell function is to create a binding between Haskell and C and from C to C++, but a easy Hello World example was not there. Unfortunatelly I couldn't found anything usefull, like an complete example, or how to compile the code from haskell to C to C++. Can sombody help me, please :P Chears, Miguel Lordelo. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ interface with Haskell
Well Isaac...I became now a little bit smarter then yesterday!!! I show you the example that I found and on which I´m working with. File: foo.hs module Foo where foreign export ccall foo :: Int - IO Int foo :: Int - IO Int foo n = return (length (f n)) f :: Int - [Int] f 0 = [] f n = n:(f (n-1)) To get the C wrapper you insert the following command: ghc -ffi -fvia-C -C foo.hs After execution you will have these following additional files: foo.hc foo.hi foo_stub.c foo_stub.h foo_stub.o What I did next was to create a file named: myfoo_c.c, where I will call the foo function (implemented in Haskell). (you can see this example on http://www.haskell.org/ghc/docs/latest/html/users_guide/ffi-ghc.html ) But the problem is to compile with gcc (must I put any flag or whatever set something) The gcc output is: myfoo_c.c:2:19: error: HsFFI.h: No such file or directory I downloaded this header file from: (I know that is not the correct way, but it was the only idea that occurs at the moment) http://www.koders.com/c/fidD0593B84C41CA71319BB079EFD0A2C80211C9337.aspx I compiled again and the following return error appears: myfoo_c.c:(.text+0x1c): undefined reference to `hs_init' myfoo_c.c:(.text+0x31): undefined reference to `foo' myfoo_c.c:(.text+0x50): undefined reference to `hs_exit' collect2: ld returned 1 exit status These functions are necessary to setup GHC runtime (see: http://www.haskell.org/ghc/docs/latest/html/users_guide/ffi-ghc.html ) What I want to know is how to compile myfoo_c.c?! Is it with GCC or GHC?! Chears, Miguel Lordelo. On Wed, Apr 16, 2008 at 9:16 PM, Isaac Dupree [EMAIL PROTECTED] wrote: perhaps haskell: foreign export foo_func foo :: Int - IO Int -- I forget the rest of the syntax here C++: extern C { int foo_func(int i); } int some_cplusplus_function() { int bat = 3; int blah = foo_func(bat); return blah; } Is that all you need to do? Miguel Lordelo wrote: Hi all, Well...somehow I'm a beginner in Haskell. But actually my interest in Haskell will increase if it is possible to call a haskell function in C++. Something like GreenCard ( http://www.haskell.org/greencard/ ) simplifying the task of interfacing Haskell programs to external libraries (usually). But is there also a task to interface a foreign language with Haskell, but calling Haskell functions. Or c2hs which is an interface generator that simplifies the development of Haskell bindings to C libraries. I want to know this, because in my company some guys are doing some testing with Frotran and MatLab and I want to show them the power of haskell and the software which we are using is implemented in C++ (there is the reason to make Haskel - C++). I read somewhere that the only way for C++ calling a haskell function is to create a binding between Haskell and C and from C to C++, but a easy Hello World example was not there. Unfortunatelly I couldn't found anything usefull, like an complete example, or how to compile the code from haskell to C to C++. Can sombody help me, please :P Chears, Miguel Lordelo. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ interface with Haskell
write the C wrapper that calls haskell, then link that to your C++ objects I think what you're really asking is how to call C from C++ -Dan 2008/4/16 Miguel Lordelo [EMAIL PROTECTED]: Hi all, Well...somehow I'm a beginner in Haskell. But actually my interest in Haskell will increase if it is possible to call a haskell function in C++. Something like GreenCard ( http://www.haskell.org/greencard/ ) simplifying the task of interfacing Haskell programs to external libraries (usually). But is there also a task to interface a foreign language with Haskell, but calling Haskell functions. Or c2hs which is an interface generator that simplifies the development of Haskell bindings to C libraries. I want to know this, because in my company some guys are doing some testing with Frotran and MatLab and I want to show them the power of haskell and the software which we are using is implemented in C++ (there is the reason to make Haskel - C++). I read somewhere that the only way for C++ calling a haskell function is to create a binding between Haskell and C and from C to C++, but a easy Hello World example was not there. Unfortunatelly I couldn't found anything usefull, like an complete example, or how to compile the code from haskell to C to C++. Can sombody help me, please :P Chears, Miguel Lordelo. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ interface with Haskell
perhaps haskell: foreign export foo_func foo :: Int - IO Int -- I forget the rest of the syntax here C++: extern C { int foo_func(int i); } int some_cplusplus_function() { int bat = 3; int blah = foo_func(bat); return blah; } Is that all you need to do? Miguel Lordelo wrote: Hi all, Well...somehow I'm a beginner in Haskell. But actually my interest in Haskell will increase if it is possible to call a haskell function in C++. Something like GreenCard ( http://www.haskell.org/greencard/ ) simplifying the task of interfacing Haskell programs to external libraries (usually). But is there also a task to interface a foreign language with Haskell, but calling Haskell functions. Or c2hs which is an interface generator that simplifies the development of Haskell bindings to C libraries. I want to know this, because in my company some guys are doing some testing with Frotran and MatLab and I want to show them the power of haskell and the software which we are using is implemented in C++ (there is the reason to make Haskel - C++). I read somewhere that the only way for C++ calling a haskell function is to create a binding between Haskell and C and from C to C++, but a easy Hello World example was not there. Unfortunatelly I couldn't found anything usefull, like an complete example, or how to compile the code from haskell to C to C++. Can sombody help me, please :P Chears, Miguel Lordelo. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ class = neutered (haskell class + haskell existential)
I was mainly specifically comparing haskell to standard OOP classes, Most OOP languages certainly have some set of other features in addition, such as forms of ad hoc polymorphism or the template meta-language of C++, or the code reuse primitives in sather, however I was mainly interested in exploring base OOP and its relation to haskell typeclasses. As it seems to come up a lot. C++ templates are a whole nother ball of wax. John -- John Meacham - ⑆repetae.net⑆john⑈ ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ class = neutered (haskell class + haskell existential)
On 8/20/06, John Meacham [EMAIL PROTECTED] wrote: C++ templates are a whole nother ball of wax. And that's putting it politely. ;-) T. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ class = neutered (haskell class + haskell existential)
John Meacham [EMAIL PROTECTED] writes: | I was mainly specifically comparing haskell to standard OOP classes, | | Most OOP languages certainly have some set of other features in addition, | such as forms of ad hoc polymorphism or the template meta-language of | C++, or the code reuse primitives in sather, however I was mainly | interested in exploring base OOP and its relation to haskell | typeclasses. As it seems to come up a lot. | | C++ templates are a whole nother ball of wax. I believe you should not eliminate C++ templates from standard OO classes -- for example, the C++ IOStream hierarchy is an example of standard OO -- at least if you want to discuss OOP with C++ :-) ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ class = neutered (haskell class + haskell existential)
John Meacham [EMAIL PROTECTED] writes: | On Tue, Aug 15, 2006 at 08:36:28PM +0200, Gabriel Dos Reis wrote: | Roughly Haskell type classes correspond to parameterized abstract | classes in C++ (i.e. class templates with virtual functions | representing the operations). Instance declarations correspond to | derivation and implementations of those parameterized classes. | | There is a major difference though, in C++ (or java, or sather, or c#, | etc..) the dictionary is always attached to the value, the actual class | data type you pass around. I suspect that most of the confusion come from the fact that people believe just because virtual functions are attached to objects, they cannot attach them to operations outside classes. That, to my surprise, hints at a deeper misappreciation of both type classes and so-called OO technology. Type classes are more OO than one might realize. The dictionary can be attached to the operations (not just to the values) by using objects local to functions (which sort of matierialize the dictionary). Consider // Abstract class for a collection of classes that implement // the Num mathematical structure templatetypename T struct Num { virtual T add(T, T) const = 0; }; // Every type must specialize this class template to assert // membership to the Num structure. templatetypename T struct Num_instance; // The operation + is defined for any type that belongs to Num. // Notice, membership is asserted aby specializing Num_instance. templatetypename T T operator+(T lhs, T rhs) { const Num_instanceT instance; return instance.add(lhs, rhs); } // Foo is in Num struct Num_instanceFoo : NumFoo { Foo add(Foo a, Foo b) const { ... } }; The key here is in the definition of operator+ which is just a formal name for the real operation done by instance.add(). I appreciate that inferring and building the dictionary (represented here by the instance local to operator+T) is done automatically by the Haskell type system. That is one of the reasons why the type class notation is a nice sugar. However, that should not distract from its deerper OO semantics. [...] | in haskell you can do | | class Monoid a where | mempty :: a | | in OOP, this cannot be done because where does the dicionary come from? See above. I believe a key in my suggestion was paramaterized abstract classes, not just abstract classes. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ class = neutered (haskell class + haskell existential)
Bulat Ziganshin [EMAIL PROTECTED] writes: | Hello John, | | Friday, August 18, 2006, 5:16:45 AM, you wrote: | | There is a major difference though, in C++ (or java, or sather, or c#, | etc..) the dictionary is always attached to the value, the actual class | data type you pass around. in haskell, the dictionary is passed | separately and the appropriae one is infered by the type system. | | your letter is damn close to that i wrote in | http://haskell.org/haskellwiki/OOP_vs_type_classes | although i mentioned not only pluses but also drawbacks of type | classes: lack of record extension mechanisms (such at that implemented | in O'Haskell) and therefore inability to reuse operation | implementation in an derived data type, lack of downcasting mechanism | (which bites me all the way), requirement to rebuild dictionaries in | polymorphic operations what is slow enough I would appreciate if you could revise the comparison based on the material I just sent, that illustrates my earlier comments. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ class = neutered (haskell class + haskell existential)
Hello John, Friday, August 18, 2006, 5:16:45 AM, you wrote: There is a major difference though, in C++ (or java, or sather, or c#, etc..) the dictionary is always attached to the value, the actual class data type you pass around. in haskell, the dictionary is passed separately and the appropriae one is infered by the type system. your letter is damn close to that i wrote in http://haskell.org/haskellwiki/OOP_vs_type_classes although i mentioned not only pluses but also drawbacks of type classes: lack of record extension mechanisms (such at that implemented in O'Haskell) and therefore inability to reuse operation implementation in an derived data type, lack of downcasting mechanism (which bites me all the way), requirement to rebuild dictionaries in polymorphic operations what is slow enough i will put your letter there and later use it to build up the final description, ok? -- Best regards, Bulatmailto:[EMAIL PROTECTED] ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ class = neutered (haskell class + haskellexistential)
Bulat Ziganshin wrote: http://haskell.org/haskellwiki/OOP_vs_type_classes although i mentioned not only pluses but also drawbacks of type classes: lack of record extension mechanisms (such at that implemented in O'Haskell) and therefore inability to reuse operation implementation in an derived data type... Hi Bulat - You can reuse ops in a derived data type but it involves a tremendous amount of boilerplate. Essentially, you just use the type classes to simulate extendable records by having a method in each class that accesses the fixed-length record corresponding to that particular C++ class. Here is an example (apologies for the length!) which shows a super class function being overridden in a derived class and a derived class method (B::Extra) making use of something implemented in the super class: module Main where {- Haskell translation of the following C++ class A { public: String s; Int i; A(String s, Int i) s(s), i(i){} virtual void Display(){ printf(A %s %d\n, s.c_str(), i); } virtual Int Reuse(){ return i * 100; } }; class B: public A{ public: Char c; B(String s, Int i, Char c) : A(s, i), c(c){} virtual void Display(){ printf(B %s %d %c, s.c_str(), i, c); } virtual void Extra(){ printf(B Extra %d\n, Reuse()); } }; -} data A = A { _A_s :: String , _A_i :: Int } -- This could do arg checking etc constructA :: String - Int - A constructA = A class ClassA a where getA :: a - A display :: a - IO () display a = do let A{_A_s = s, _A_i = i} = getA a putStrLn $ A ++ s ++ show i reuse :: a - Int reuse a = _A_i (getA a) * 100 data WrapA = forall a. ClassA a = WrapA a instance ClassA WrapA where getA (WrapA a) = getA a display (WrapA a) = display a reuse (WrapA a) = reuse a instance ClassA A where getA = id data B = B { _B_A :: A, _B_c :: Char } constructB :: String - Int - Char - B constructB s i c = B {_B_A = constructA s i, _B_c = c} class ClassA b = ClassB b where getB :: b - B extra :: b - IO () extra b = do putStrLn $ B Extra ++ show (reuse b) data WrapB = forall b. ClassB b = WrapB b instance ClassB WrapB where getB (WrapB b) = getB b extra (WrapB b) = extra b instance ClassA WrapB where getA (WrapB b) = getA b display (WrapB b) = display b reuse (WrapB b) = reuse b instance ClassB B where getB = id instance ClassA B where getA = _B_A -- override the base class version display b = putStrLn $ B ++ _A_s (getA b) ++ show (_A_i (getA b)) ++ [_B_c (getB b)] main :: IO () main = do let a = constructA a 0 b = constructB b 1 '*' col = [WrapA a, WrapA b] mapM_ display col putStrLn mapM_ (putStrLn . show . reuse) col putStrLn extra b {- Output: ghc -fglasgow-exts --make Main main A a0 B b1* 0 100 B Extra 100 -} (If the caseless underscore Haskell' ticket is accepted the leading underscores would have to be replaced by something like _f ie _A_s --- _fA_s etc) Regards, Brian. -- Logic empowers us and Love gives us purpose. Yet still phantoms restless for eras long past, congealed in the present in unthought forms, strive mightily unseen to destroy us. http://www.metamilk.com ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ class = neutered (haskell class + haskell existential)
On 8/18/06, John Meacham [EMAIL PROTECTED] wrote: [lots of good argument before and after deleted] There is a major difference though, in C++ (or java, or sather, or c#, etc..) the dictionary is always attached to the value, the actual class data type you pass around. in haskell, the dictionary is passed separately and the appropriae one is infered by the type system. C++ doesn't infer, it just assumes everything will be carying around its dictionary with it. C++ programmers deal with this using a number of techniques, mostly involving templates. Actually, there is one technique using C++ templates that I really want to see going mainstream in the Haskell implementations. Existential types are already there, now I want to see associated types (trait types in C++). Maybe I've been doing too much C++ programming in the last few years, but a lot of the times when I end up using multiparameter type classes, what I really want is an associated type. For example class Monad s = Store s where type Key insert :: Binary - s Key retrStore :: Key - s Binary ... so that part of the instance is a choice of the key type. For those who are interested, I'm sure the relevant papers are readily available on citeseer/Google. :-) Tom ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ parser in Haskell?
On Wed, Apr 19, 2006 at 11:01:03PM +0200, Christophe Poucet wrote: For the parsing and lexing I used happy and alex. Jake Luck wrote: I would be very interested in this as well. I have looked myself but haven't found anything else. I wrote one myself in Haskell but for a subset of C++ (subset of C but with some extra things like methods). Me, too.. Id' like to write some omnicompletion functions for vim for different languages.. (Java, C, C++, haskell).. But I'm still busy with other things. I think it would be easy to extend Parsec for something similar to ? not returning what to expect but completion items... Don't know about happy yet. Marc ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ parser in Haskell?
I would be very interested in this as well. I have looked myself but haven't found anything else. I wrote one myself in Haskell but for a subset of C++ (subset of C but with some extra things like methods). Christophe Poucet Ravi Nanavati wrote: It turns out we might find such a beast useful at Bluespec. If anyone has written a C++ parser in Haskell (or knows of one), we'd like to hear about it. Thanks, - Ravi Nanavati Bluespec, Inc. ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ parser in Haskell?
I would be very interested in this as well. I have looked myself but haven't found anything else. I wrote one myself in Haskell but for a subset of C++ (subset of C but with some extra things like methods). Did you build it using parsec or happy? jake ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C++ parser in Haskell?
For the parsing and lexing I used happy and alex. Jake Luck wrote: I would be very interested in this as well. I have looked myself but haven't found anything else. I wrote one myself in Haskell but for a subset of C++ (subset of C but with some extra things like methods). Did you build it using parsec or happy? jake ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe -- Christophe Poucet Ph.D. Student Phone:+32 16 28 87 20 E-mail: [EMAIL PROTECTED] IMEC vzw – Register of Legal Entities Leuven VAT BE 0425.260.668 – Kapeldreef 75, B-3001 Leuven, Belgium – www.imec.be *DISCLAIMER* This e-mail and/or its attachments may contain confidential information. It is intended solely for the intended addressee(s). Any use of the information contained herein by other persons is prohibited. IMEC vzw does not accept any liability for the contents of this e-mail and/or its attachments. ** ___ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C Bindings?
Hi, The Foreign Function Interface (FFI) is your friend for these tasks: http://www.cse.unsw.edu.au/~chak/haskell/ffi/ On the haskell.org web page, under libraries and tools there are links to a number of tools to help you connect your C haskell programs. The GreenCard and c-haskell tools seem to be used by a number of people. Alastair Reid's Guide to Haskell's Foreign Function Interface, http://www.reid-consulting-uk.ltd.uk/docs/ffi.html is a good place to start. It has some comparison of the various tools. Best Wishes, Greg On Apr 13, 2004, at 12:56 PM, Russ Lewis wrote: Does Haskell have some mechanism that allows it to link to C, or other imperative languages? I know, you could use the IO Monad to do it...using stdin and stdout as pipes to any other program. But is there a way to link Haskell into a C program? Thanks again for the help for a newbie... Russ ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe
Re: [Haskell-cafe] C Bindings?
It's not really newbie stuff, but maybe this is what you're looking for: http://www.cse.unsw.edu.au/~chak/haskell/ffi/ #g -- At 09:56 13/04/04 -0700, Russ Lewis wrote: Does Haskell have some mechanism that allows it to link to C, or other imperative languages? I know, you could use the IO Monad to do it...using stdin and stdout as pipes to any other program. But is there a way to link Haskell into a C program? Thanks again for the help for a newbie... Russ ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe Graham Klyne For email: http://www.ninebynine.org/#Contact ___ Haskell-Cafe mailing list [EMAIL PROTECTED] http://www.haskell.org/mailman/listinfo/haskell-cafe