Search Results

Search found 4547 results on 182 pages for 'haskell io'.

Page 2/182 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • A programming language that does not allow IO. Haskell is not a pure language

    - by TheIronKnuckle
    (I asked this on Stack Overflow and it got closed as off-topic, I was a bit confused until I read the FAQ, which discouraged subjective theoratical debate style questions. The FAQ here doesn't seem to have a problem with it and it sounds like this is a more appropriate place to post. If this gets closed again, forgive me, I'm not trying to troll) Are there any 100% pure languages (as I describe in the Stack Overflow post) out there already and if so, could they feasibly be used to actually do stuff? i.e. do they have an implementation? I'm not looking for raw maths on paper/Pure lambda calculus. However Pure lambda calculus with a compiler or a runtime system attached is something I'd be interested in hearing about.

    Read the article

  • System.IO.IOException: file used by another process

    - by Srodriguez
    Dear all, I've been working in this small piece of code that seems trivial but still i cannot really see where is the problem. My functions does a pretty simple thing. Opens a file, copy its contents, replace a string inside and copy it back to the original file (a simple search and replace inside a text file then). I didn't really know how to do that as I'm adding lines to the original file, so i just create a copy of the file, (file.temp) copy also a backup (file.temp) then delete the original file(file) and copy the file.temp to file. I get an exception while doing the delete of the file. Here is the sample code: private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod) { Boolean result = false; FileStream fs = new FileStream(file.FullName + ".tmp", FileMode.Create, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); StreamReader streamreader = file.OpenText(); String originalPath = file.FullName; string input = streamreader.ReadToEnd(); Console.WriteLine("input : {0}", input); String tempString = input.Replace(extractedMethod, modifiedMethod); Console.WriteLine("replaced String {0}", tempString); try { sw.Write(tempString); sw.Flush(); sw.Close(); sw.Dispose(); fs.Close(); fs.Dispose(); streamreader.Close(); streamreader.Dispose(); File.Copy(originalPath, originalPath + ".old", true); FileInfo newFile = new FileInfo(originalPath + ".tmp"); File.Delete(originalPath); File.Copy(fs., originalPath, true); result = true; } catch (Exception ex) { Console.WriteLine(ex); } return result; }` And the related exception System.IO.IOException: The process cannot access the file 'E:\mypath\myFile.cs' because it is being used by another process. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.File.Delete(String path) at callingMethod.modifyFile(FileInfo file, String extractedMethod, String modifiedMethod) Normally these errors come from unclosed file streams, but I've taken care of that. I guess I've forgotten an important step but cannot figure out where. Thank you very much for your help,

    Read the article

  • node.js / socket.io, cookies only working locally

    - by Ben Griffiths
    I'm trying to use cookie based sessions, however it'll only work on the local machine, not over the network. If I remove the session related stuff, it will however work just great over the network... You'll have to forgive the lack of quality code here, I'm just starting out with node/socket etc etc, and finding any clear guides is tough going, so I'm in n00b territory right now. Basically this is so far hacked together from various snippets with about 10% understanding of what I'm actually doing... The error I see in Chrome is: socket.io.js:1632GET http://192.168.0.6:8080/socket.io/1/?t=1334431940273 500 (Internal Server Error) Socket.handshake ------- socket.io.js:1632 Socket.connect ------- socket.io.js:1671 Socket ------- socket.io.js:1530 io.connect ------- socket.io.js:91 (anonymous function) ------- /socket-test/:9 jQuery.extend.ready ------- jquery.js:438 And in the console for the server I see: debug - served static content /socket.io.js debug - authorized warn - handshake error No cookie My server is: var express = require('express') , app = express.createServer() , io = require('socket.io').listen(app) , connect = require('express/node_modules/connect') , parseCookie = connect.utils.parseCookie , RedisStore = require('connect-redis')(express) , sessionStore = new RedisStore(); app.listen(8080, '192.168.0.6'); app.configure(function() { app.use(express.cookieParser()); app.use(express.session( { secret: 'YOURSOOPERSEKRITKEY', store: sessionStore })); }); io.configure(function() { io.set('authorization', function(data, callback) { if(data.headers.cookie) { var cookie = parseCookie(data.headers.cookie); sessionStore.get(cookie['connect.sid'], function(err, session) { if(err || !session) { callback('Error', false); } else { data.session = session; callback(null, true); } }); } else { callback('No cookie', false); } }); }); var users_count = 0; io.sockets.on('connection', function (socket) { console.log('New Connection'); var session = socket.handshake.session; ++users_count; io.sockets.emit('users_count', users_count); socket.on('something', function(data) { io.sockets.emit('doing_something', data['data']); }); socket.on('disconnect', function() { --users_count; io.sockets.emit('users_count', users_count); }); }); My page JS is: jQuery(function($){ var socket = io.connect('http://192.168.0.6', { port: 8080 } ); socket.on('users_count', function(data) { $('#client_count').text(data); }); socket.on('doing_something', function(data) { if(data == '') { window.setTimeout(function() { $('#target').text(data); }, 3000); } else { $('#target').text(data); } }); $('#textbox').keydown(function() { socket.emit('something', { data: 'typing' }); }); $('#textbox').keyup(function() { socket.emit('something', { data: '' }); }); });

    Read the article

  • Is Haskell's type system an obstacle to understanding functional programming?

    - by FarmBoy
    I'm studying Haskell for the purpose of understanding functional programming, with the expectation that I'll apply the insight that I gain in other languages (Groovy, Python, JavaScript mainly.) I choose Haskell because I had the impression that it is very purely functional, and wouldn't allow for any reliance on state. I did not choose to learn Haskell because I was interested in navigating an extremely rigid type system. My question is this: Is a strong type system a necessary by-product of an extremely pure functional language, or is this an unrelated design choice particular to Haskell? If it is the latter, I'm curious what would be the most purely functional language that is dynamically typed. I'm not particularly opposed to strong typing, it has its place, but I'm having a hard time seeing how it benefits me in this educational endeavor.

    Read the article

  • Is Haskell's type system an obstacle to understanding functional programming?

    - by Eric Wilson
    I'm studying Haskell for the purpose of understanding functional programming, with the expectation that I'll apply the insight that I gain in other languages (Groovy, Python, JavaScript mainly.) I choose Haskell because I had the impression that it is very purely functional, and wouldn't allow for any reliance on state. I did not choose to learn Haskell because I was interested in navigating an extremely rigid type system. My question is this: Is a strong type system a necessary by-product of an extremely pure functional language, or is this an unrelated design choice particular to Haskell? If it is the latter, I'm curious what would be the most purely functional language that is dynamically typed. I'm not particularly opposed to strong typing, it has its place, but I'm having a hard time seeing how it benefits me in this educational endeavor.

    Read the article

  • Is return-type-(only)-polymorphism in Haskell a good thing?

    - by dainichi
    One thing that I've never quite come to terms with in Haskell is how you can have polymorphic constants and functions whose return type cannot be determined by their input type, like class Foo a where foo::Int -> a Some of the reasons that I do not like this: Referential transparency: "In Haskell, given the same input, a function will always return the same output", but is that really true? read "3" return 3 when used in an Int context, but throws an error when used in a, say, (Int,Int) context. Yes, you can argue that read is also taking a type parameter, but the implicitness of the type parameter makes it lose some of its beauty in my opinion. Monomorphism restriction: One of the most annoying things about Haskell. Correct me if I'm wrong, but the whole reason for the MR is that computation that looks shared might not be because the type parameter is implicit. Type defaulting: Again one of the most annoying things about Haskell. Happens e.g. if you pass the result of functions polymorphic in their output to functions polymorphic in their input. Again, correct me if I'm wrong, but this would not be necessary without functions whose return type cannot be determined by their input type (and polymorphic constants). So my question is (running the risk of being stamped as a "discussion quesion"): Would it be possible to create a Haskell-like language where the type checker disallows these kinds of definitions? If so, what would be the benefits/disadvantages of that restriction? I can see some immediate problems: If, say, 2 only had the type Integer, 2/3 wouldn't type check anymore with the current definition of /. But in this case, I think type classes with functional dependencies could come to the rescue (yes, I know that this is an extension). Furthermore, I think it is a lot more intuitive to have functions that can take different input types, than to have functions that are restricted in their input types, but we just pass polymorphic values to them. The typing of values like [] and Nothing seems to me like a tougher nut to crack. I haven't thought of a good way to handle them. I doubt I am the first person to have had thoughts like these. Does anybody have links to good discussions about this Haskell design decision and the pros/cons of it?

    Read the article

  • eclipseFP2 haskell unix haveing issues connectiong to Scion Server

    - by Chris
    I am having troubles with using FP2 for eclipse and getting it to connect with the server. Eclipse seems to auto-detect scion_server, but I a error in the log file !ENTRY net.sf.eclipsefp.haskell.scion.client 4 4 2010-04-15 10:40:06.580 !MESSAGE The connection with the Scion server could not be established. !STACK 0 The connection with the Scion server could not be established. at net.sf.eclipsefp.haskell.scion.internal.client.ScionServer.connectToServer(ScionServer.java:328) at net.sf.eclipsefp.haskell.scion.internal.client.ScionServer.startServer(ScionServer.java:73) at net.sf.eclipsefp.haskell.scion.client.ScionInstance.start(ScionInstance.java:94) at net.sf.eclipsefp.haskell.scion.client.ScionInstance.runCommandSync(ScionInstance.java:207) at net.sf.eclipsefp.haskell.scion.internal.commands.ScionCommand.run(ScionCommand.java:136) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Caused by: java.net.ConnectException: Connection refused at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(Unknown Source) at java.net.PlainSocketImpl.connectToAddress(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.<init>(Unknown Source) at java.net.Socket.<init>(Unknown Source) at net.sf.eclipsefp.haskell.scion.internal.client.ScionServer.connectToServer(ScionServer.java:345) at net.sf.eclipsefp.haskell.scion.internal.client.ScionServer.connectToServer(ScionServer.java:324)

    Read the article

  • java IO to copy one File to another

    - by Aly
    I have two Java.io.File objects file1 and file2. I want to copy the contents from file1 to file2. Is there an standard way to do this without me having to create a method that reads file1 and write to file2

    Read the article

  • Resources for finding Haskell jobs?

    - by Dan
    Where is a good place to go to find a job where I can (frequently) use Haskell? Just to be clear, I am not asking: What's the Haskell market like? Why is Haskell used so little in the industry? What is Haskell actually useful for? Nor am I asking you to tell me that Haskell jobs can't be found. That is the default conclusion if no good responses show up here. I am asking, for the 2 or 3 Haskell jobs that are out there, how can I find them?

    Read the article

  • Getting ZFS per dataset IO statistics (or NFS per export IO statistics)

    - by jkj
    Where do I find statistics about how IO is divided between zfs datasets? (zpool iostat only tells me how much IO a pool is experiencing.) All the relevant datasets are used through NFS, so I'd be happy with per export NFS IO statistics also. We're currently running OpenIndiana [edit] It seems that operation and byte counter are available in kstat kstat -p unix:*:vopstats_??????? ... unix:0:vopstats_2d90002:nputpage 50 unix:0:vopstats_2d90002:nread 12390785 ... unix:0:vopstats_2d90002:read_bytes 22272845340 unix:0:vopstats_2d90002:readdir_bytes 477996168 ... ...but the strange hexadecimal ID numbers have to be resolved from /etc/mnttab (better ideas?) rpool/export/home/jkj /export/home/jkj zfs rw,...,dev=2d90002 1308471917 Now writing a munin plugin to use the data...

    Read the article

  • Scheme vs Haskell for an Introduction to Functional Programming?

    - by haziz
    I am comfortable with programming in C and C#, and will explore C++ in the future. I may be interested in exploring functional programming as a different programming paradigm. I am doing this for fun, my job does not involve computer programming, and am somewhat inspired by the use of functional programming, taught fairly early, in computer science courses in college. Lambda calculus is certainly beyond my mathematical abilities, but I think I can handle functional programming. Which of Haskell or Scheme would serve as a good intro to functional programming? I use emacs as my text editor and would like to be able to configure it more easily in the future which would entail learning Emacs Lisp. My understanding, however, is that Emacs Lisp is fairly different from Scheme and is also more procedural as opposed to functional. I would likely be using "The Little Schemer" book, which I have already bought, if I pursue Scheme (seems to me a little weird from my limited leafing through it). Or would use the "Learn You a Haskell for Great Good" if I pursue Haskell. I would also watch the Intro to Haskell videos by Dr Erik Meijer on Channel 9. Any suggestions, feedback or input appreciated. Thanks. P.S. BTW I also have access to F# since I have Visual Studio 2010 which I use for C# development, but I don't think that should be my main criteria for selecting a language.

    Read the article

  • How often is seq used in Haskell production code?

    - by Giorgio
    I have some experience writing small tools in Haskell and I find it very intuitive to use, especially for writing filters (using interact) that process their standard input and pipe it to standard output. Recently I tried to use one such filter on a file that was about 10 times larger than usual and I got a Stack space overflow error. After doing some reading (e.g. here and here) I have identified two guidelines to save stack space (experienced Haskellers, please correct me if I write something that is not correct): Avoid recursive function calls that are not tail-recursive (this is valid for all functional languages that support tail-call optimization). Introduce seq to force early evaluation of sub-expressions so that expressions do not grow to large before they are reduced (this is specific to Haskell, or at least to languages using lazy evaluation). After introducing five or six seq calls in my code my tool runs smoothly again (also on the larger data). However, I find the original code was a bit more readable. Since I am not an experienced Haskell programmer I wanted to ask if introducing seq in this way is a common practice, and how often one will normally see seq in Haskell production code. Or are there any techniques that allow to avoid using seq too often and still use little stack space?

    Read the article

  • Haskell, mongodb, date

    - by r.sendecky
    How would I insert or auto insert date into mongodb from haskell? What is the best way to convert from mongo date type to haskell data type? Say, in a situation where I insert blog post records (any haskell web framework) and I want to date stamp every record automatically. How would I go about it? The question is more about type conversion and mongodb date type creation from within haskell driver.

    Read the article

  • What can Haskell's type system do that Java's can't?

    - by Matt Fenwick
    I was talking to a friend about the differences between the type systems of Haskell and Java. He asked me what Haskell's could do that Java's couldn't, and I realized that I didn't know. After thinking for a while, I came up with a very short list of minor differences. Not being heavy into type theory, I'm left wondering whether they're formally equivalent. To try and keep this from becoming a subjective question, I'm asking: what are the major, non-syntactical differences between their type systems? I realize some things are easier/harder in one than in the other, and I'm not interested in talking about those. And to make it more specific, let's ignore Haskell type extensions since there's so many out there that do all kinds of crazy/cool stuff.

    Read the article

  • What can Haskell's type system do that Java's can't and vice versa?

    - by Matt Fenwick
    I was talking to a friend about the differences between the type systems of Haskell and Java. He asked me what Haskell's could do that Java's couldn't, and I realized that I didn't know. After thinking for a while, I came up with a very short list of minor differences. Not being heavy into type theory, I'm left wondering whether they're formally equivalent. To try and keep this from becoming a subjective question, I'm asking: what are the major, non-syntactical differences between their type systems? I realize some things are easier/harder in one than in the other, and I'm not interested in talking about those. And to make it more specific, let's ignore Haskell type extensions since there's so many out there that do all kinds of crazy/cool stuff.

    Read the article

  • Why C# is not statically typed but F# and Haskell are?

    - by ??????? ???????
    There was a talk given by Brian Hurt about advantages and disadvantages of static typing. Brian said that by static typing he don't mean C#, but F# and Haskell. Is it because of dynamic keyword added to C#-4.0? But this feature is relatively rarely useful. By the way, there are ? and unsafeCoerse in Haskell which obviously are not the same, but something that could blown your head off in runtime similarly like exception thrown as a result of dynamic. Finally, why F# and Haskell could be named a statically typed languages and C# couldn't?

    Read the article

  • Is there an imperative language with a Haskell-like type system?

    - by Graham Kaemmer
    I've tried to learn Haskell a few times over the last few years, and, maybe because I know mainly scripting languages, the functional-ness of it has always bothered me (monads seem like a huge mess for doing lots of I/O). However, I think it's type system is perfect. Reading through a guide to Haskell's types and typeclasses (like this), I don't really see a reason why they would require a functional language, and furthermore, they seem like they would be perfect for an industry-grade object-oriented language (like Java). This all begs the question: has anyone ever taken Haskell's typing system and made a imperative, OOP language with it? If so, I want to use it.

    Read the article

  • Type patterns and generic classes in Haskell

    - by finnsson
    I'm trying to understand type patterns and generic classes in Haskell but can't seem to get it. Could someone explain it in laymen's terms? In [1] I've read that "To apply functions generically to all data types, we view data types in a uniform manner: except for basic predefined types such as Float, IO, and ?, every Haskell data type can be viewed as a labeled sum of possibly labeled products." and then Unit, :*: and :+: are mentioned. Are all data types in Haskell automatically versions of the above mentioned and if so how do I figure out how a specific data type is represented in terms of :*:, etc? The users guide for generic classes (ch. 7.16) at haskell.org doesn't mention the predefined types but shouldn't they be handled in every function if the type patterns should be exhaustive? [1] Comparing Approaches to Generic Programming in Haskell, Ralf Hinze, Johan Jeuring, and Andres Löh

    Read the article

  • Optimizing Haskell code

    - by Masse
    I'm trying to learn Haskell and after an article in reddit about Markov text chains, I decided to implement Markov text generation first in Python and now in Haskell. However I noticed that my python implementation is way faster than the Haskell version, even Haskell is compiled to native code. I am wondering what I should do to make the Haskell code run faster and for now I believe it's so much slower because of using Data.Map instead of hashmaps, but I'm not sure I'll post the Python code and Haskell as well. With the same data, Python takes around 3 seconds and Haskell is closer to 16 seconds. It comes without saying that I'll take any constructive criticism :). import random import re import cPickle class Markov: def __init__(self, filenames): self.filenames = filenames self.cache = self.train(self.readfiles()) picklefd = open("dump", "w") cPickle.dump(self.cache, picklefd) picklefd.close() def train(self, text): splitted = re.findall(r"(\w+|[.!?',])", text) print "Total of %d splitted words" % (len(splitted)) cache = {} for i in xrange(len(splitted)-2): pair = (splitted[i], splitted[i+1]) followup = splitted[i+2] if pair in cache: if followup not in cache[pair]: cache[pair][followup] = 1 else: cache[pair][followup] += 1 else: cache[pair] = {followup: 1} return cache def readfiles(self): data = "" for filename in self.filenames: fd = open(filename) data += fd.read() fd.close() return data def concat(self, words): sentence = "" for word in words: if word in "'\",?!:;.": sentence = sentence[0:-1] + word + " " else: sentence += word + " " return sentence def pickword(self, words): temp = [(k, words[k]) for k in words] results = [] for (word, n) in temp: results.append(word) if n > 1: for i in xrange(n-1): results.append(word) return random.choice(results) def gentext(self, words): allwords = [k for k in self.cache] (first, second) = random.choice(filter(lambda (a,b): a.istitle(), [k for k in self.cache])) sentence = [first, second] while len(sentence) < words or sentence[-1] is not ".": current = (sentence[-2], sentence[-1]) if current in self.cache: followup = self.pickword(self.cache[current]) sentence.append(followup) else: print "Wasn't able to. Breaking" break print self.concat(sentence) Markov(["76.txt"]) -- module Markov ( train , fox ) where import Debug.Trace import qualified Data.Map as M import qualified System.Random as R import qualified Data.ByteString.Char8 as B type Database = M.Map (B.ByteString, B.ByteString) (M.Map B.ByteString Int) train :: [B.ByteString] -> Database train (x:y:[]) = M.empty train (x:y:z:xs) = let l = train (y:z:xs) in M.insertWith' (\new old -> M.insertWith' (+) z 1 old) (x, y) (M.singleton z 1) `seq` l main = do contents <- B.readFile "76.txt" print $ train $ B.words contents fox="The quick brown fox jumps over the brown fox who is slow jumps over the brown fox who is dead."

    Read the article

  • Do any languages other than haskell/agda have a hindley-milner type system and type classes?

    - by Jimmy Hoffa
    In pondering what gives Haskell such a layer of mental pain in becoming proficient the main thing I can think of are the Monads, Applicatives, Functors, and gaining an intuition to know how a list or maybe will behave in regards to sequence or alternate or bind etc. But why haven't other languages presented these same concepts given the usefulness of monads/applicatives/etc? It occurs to me, type classes are the key, so the question is: Have any languages other than Haskell/Agda actually implemented type classes in the same or similar way?

    Read the article

  • In Haskell, I want to read a file and then write to it. Do I need strictness annotation?

    - by Steve
    Hi, Still quite new to Haskell.. I want to read the contents of a file, do something with it possibly involving IO (using putStrLn for now) and then write new contents to the same file. I came up with: doit :: String -> IO () doit file = do contents <- withFile tagfile ReadMode $ \h -> hGetContents h putStrLn contents withFile tagfile WriteMode $ \h -> hPutStrLn h "new content" However this doesn't work due to laziness. The file contents are not printed. I found this post which explains it well. The solution proposed there is to include putStrLn within the withFile: doit :: String -> IO () doit file = do withFile tagfile ReadMode $ \h -> do contents <- hGetContents h putStrLn contents withFile tagfile WriteMode $ \h -> hPutStrLn h "new content" This works, but it's not what I want to do. The operation in I will eventually replace putStrLn might be long, I don't want to keep the file open the whole time. In general I just want to be able to get the file content out and then close it before working with that content. The solution I came up with is the following: doit :: String -> IO () doit file = do c <- newIORef "" withFile tagfile ReadMode $ \h -> do a <- hGetContents h writeIORef c $! a d <- readIORef c putStrLn d withFile tagfile WriteMode $ \h -> hPutStrLn h "Test" However, I find this long and a bit obfuscated. I don't think I should need an IORef just to get a value out, but I needed "place" to put the file contents. Also, it still didn't work without the strictness annotation $! for writeIORef. I guess IORefs are not strict by nature? Can anyone recommend a better, shorter way to do this while keeping my desired semantics? Thanks!

    Read the article

  • Instantiate type variable in Haskell

    - by danportin
    EDIT: Solved. I was unware that enabling a language extension in the source file did not enable the language extension in GHCi. The solution was to :set FlexibleContexts in GHCi. I recently discovered that type declarations in classes and instances in Haskell are Horn clauses. So I encoded the arithmetic operations from The Art of Prolog, Chapter 3, into Haskell. For instance: fac(0,s(0)). fac(s(N),F) :- fac(N,X), mult(s(N),X,F). class Fac x y | x -> y instance Fac Z (S Z) instance (Fac n x, Mult (S n) x f) => Fac (S n) f pow(s(X),0,0) :- nat(X). pow(0,s(X),s(0)) :- nat(X). pow(s(N),X,Y) :- pow(N,X,Z), mult(Z,X,Y). class Pow x y z | x y -> z instance (N n) => Pow (S n) Z Z instance (N n) => Pow Z (S n) (S Z) instance (Pow n x z, Mult z x y) => Pow (S n) x y In Prolog, values are insantiated for (logic) variable in a proof. However, I don't understand how to instantiate type variables in Haskell. That is, I don't understand what the Haskell equivalent of a Prolog query ?-f(X1,X2,...,Xn) is. I assume that :t undefined :: (f x1 x2 ... xn) => xi would cause Haskell to instantiate xi, but this gives a Non type-variable argument in the constraint error, even with FlexibleContexts enabled.

    Read the article

  • How "healthy" is the haskell community

    - by Asher
    I came across a post where someone wrote something inaccurate about haskell (won't go into it) and he got flammed for it. Which (pleasantly) surprised me. About 3 years ago I read this joke about haskell: All the haskell programmers in the world can fit into a 747 and if that plane were to crash no one would care... or something along those lines. Which brings me to my question: is haskell "mainstream"? Is it mainly used by hobbiest and academics or someone making some serious money from it (which is the true yardstick of how good a language is - just kidding, geez!)?

    Read the article

  • Bubble sort algorithm implementations (Haskell vs. C)

    - by kingping
    Hello. I have written 2 implementation of bubble sort algorithm in C and Haskell. Haskell implementation: module Main where main = do contents <- readFile "./data" print "Data loaded. Sorting.." let newcontents = bubblesort contents writeFile "./data_new_ghc" newcontents print "Sorting done" bubblesort list = sort list [] False rev = reverse -- separated. To see rev2 = reverse -- who calls the routine sort (x1:x2:xs) acc _ | x1 > x2 = sort (x1:xs) (x2:acc) True sort (x1:xs) acc flag = sort xs (x1:acc) flag sort [] acc True = sort (rev acc) [] False sort _ acc _ = rev2 acc I've compared these two implementations having run both on file with size of 20 KiB. C implementation took about a second, Haskell — about 1 min 10 sec. I have also profiled the Haskell application: Compile for profiling: C:\Temp ghc -prof -auto-all -O --make Main Profile: C:\Temp Main.exe +RTS -p and got these results. This is a pseudocode of the algorithm: procedure bubbleSort( A : list of sortable items ) defined as: do swapped := false for each i in 0 to length(A) - 2 inclusive do: if A[i] > A[i+1] then swap( A[i], A[i+1] ) swapped := true end if end for while swapped end procedure I wonder if it's possible to make Haskell implementation work faster without changing the algorithm (there's are actually a few tricks to make it work faster, but neither implementations have these optimizations)

    Read the article

  • F# for C#/Haskell programmer

    - by Maciej Piechotka
    What is recommended tutorial of F# for Haskell programmer? F# seems to borrow a lot from Haskell but there are little traps which makes hard to write. Generally I need walkthrough the F# which would not explain what is the difference between mutable data and immutable (Haskell is much more strict in this area) etc. I know C# a little so I know more or less what .Net is about as well.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >