Search Results

Search found 2222 results on 89 pages for 'functional'.

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

  • functional dependencies vs type families

    - by mhwombat
    I'm developing a framework for running experiments with artificial life, and I'm trying to use type families instead of functional dependencies. Type families seems to be the preferred approach among Haskellers, but I've run into a situation where functional dependencies seem like a better fit. Am I missing a trick? Here's the design using type families. (This code compiles OK.) {-# LANGUAGE TypeFamilies, FlexibleContexts #-} import Control.Monad.State (StateT) class Agent a where agentId :: a -> String liveALittle :: Universe u => a -> StateT u IO a -- plus other functions class Universe u where type MyAgent u :: * withAgent :: (MyAgent u -> StateT u IO (MyAgent u)) -> String -> StateT u IO () -- plus other functions data SimpleUniverse = SimpleUniverse { mainDir :: FilePath -- plus other fields } defaultWithAgent :: (MyAgent u -> StateT u IO (MyAgent u)) -> String -> StateT u IO () defaultWithAgent = undefined -- stub -- plus default implementations for other functions -- -- In order to use my framework, the user will need to create a typeclass -- that implements the Agent class... -- data Bug = Bug String deriving (Show, Eq) instance Agent Bug where agentId (Bug s) = s liveALittle bug = return bug -- stub -- -- .. and they'll also need to make SimpleUniverse an instance of Universe -- for their agent type. -- instance Universe SimpleUniverse where type MyAgent SimpleUniverse = Bug withAgent = defaultWithAgent -- boilerplate -- plus similar boilerplate for other functions Is there a way to avoid forcing my users to write those last two lines of boilerplate? Compare with the version using fundeps, below, which seems to make things simpler for my users. (The use of UndecideableInstances may be a red flag.) (This code also compiles OK.) {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances #-} import Control.Monad.State (StateT) class Agent a where agentId :: a -> String liveALittle :: Universe u a => a -> StateT u IO a -- plus other functions class Universe u a | u -> a where withAgent :: Agent a => (a -> StateT u IO a) -> String -> StateT u IO () -- plus other functions data SimpleUniverse = SimpleUniverse { mainDir :: FilePath -- plus other fields } instance Universe SimpleUniverse a where withAgent = undefined -- stub -- plus implementations for other functions -- -- In order to use my framework, the user will need to create a typeclass -- that implements the Agent class... -- data Bug = Bug String deriving (Show, Eq) instance Agent Bug where agentId (Bug s) = s liveALittle bug = return bug -- stub -- -- And now my users only have to write stuff like... -- u :: SimpleUniverse u = SimpleUniverse "mydir"

    Read the article

  • Should "closed as duplicate" software programming be extreme or functional? [migrated]

    - by Web Developer
    I'm a web developer loving this site for it's potential, and it's Coffee look . I was reading a great question, that is this: click here and noticed 8 moderators tagged it as DUPLICATED! The question was closed! Obviously it isn't and I'm going to explain why if needed but it can be seen: the question is unique, is the case/story of a young who have SPECIFIC experience with C++ , VB and Assembler and asking, knowing this specifications an answer (It is not a general question like "hey I'm young can I do the programmer??") Let me know your opinion! do you think this question should or should not be closed? And let's think about also the people not only the "data" and "cases covered" ... do you think this is important too? or is better to keep a place where people doesn't count?

    Read the article

  • How do functional languages handle a mocking situation when using Interface based design?

    - by Programmin Tool
    Typically in C# I use dependency injection to help with mocking; public void UserService { public UserService(IUserQuery userQuery, IUserCommunicator userCommunicator, IUserValidator userValidator) { UserQuery = userQuery; UserValidator = userValidator; UserCommunicator = userCommunicator; } ... public UserResponseModel UpdateAUserName(int userId, string userName) { var result = UserValidator.ValidateUserName(userName) if(result.Success) { var user = UserQuery.GetUserById(userId); if(user == null) { throw new ArgumentException(); user.UserName = userName; UserCommunicator.UpdateUser(user); } } ... } ... } public class WhenGettingAUser { public void AndTheUserDoesNotExistThrowAnException() { var userQuery = Substitute.For<IUserQuery>(); userQuery.GetUserById(Arg.Any<int>).Returns(null); var userService = new UserService(userQuery); AssertionExtensions.ShouldThrow<ArgumentException>(() => userService.GetUserById(-121)); } } Now in something like F#: if I don't go down the hybrid path, how would I test workflow situations like above that normally would touch the persistence layer without using Interfaces/Mocks? I realize that every step above would be tested on its own and would be kept as atomic as possible. Problem is that at some point they all have to be called in line, and I'll want to make sure everything is called correctly.

    Read the article

  • functional-style datatypes in Python

    - by Danny Roberts
    For anyone who's spent some time with sml, ocaml, haskell, etc. when you go back to using C, Python, Java, etc. you start to notice things you never knew were missing. I'm doing some stuff in Python and I realized what I really want is a functional-style datatype like (for example) datatype phoneme = Vowel of string | Consonant of voice * place * manner datatype voice = Voiced | Voiceless datatype place = Labial | Dental | Retroflex | Palatal | Velar | Glottal datatype manner = Stop | Affricate | Fricative | Nasal | Lateral type syllable = phoneme list Does anyone have a particular way that they like to simulate this in Python?

    Read the article

  • Seeking Functional Programming Lexicon

    - by Randall Schulz
    Hi, Knowing the argot of a field helps me a lot, especially since it allows me to converse intelligently with those who know a lot more than I, so I would like to find a good lexicon of Functional Programming terms. E.g., I repeatedly encounter these: Functor, Arrow, Category, Kleisli, Monad, Monoid, a veritable zoo of Morphisms, etc. I also notice many of these appear with prefixes such as "covariant", "co-", "endo-" etc. Of these, I can say I actually understand Monoid and Covariant and sort of get Monad, but the rest are still gibberish to me. (Note that I don't mean this list as exhaustive and I'm not looking to have these defined or described for me here, I'm looking for learning resources.) Can someone point me towards an FP lexicon? It need not be on-line, as long as it's possible to find it (and it's not a rare volume for which I'd have to pay many tens of dollars).

    Read the article

  • Setting up functional Tests in Flex

    - by Dan Monego
    I'm setting up a functional test suite for an application that loads an external configuration file. Right now, I'm using flexunit's addAsync function to load it and then again to test if the contents point to services that exist and can be accessed. The trouble with this is that having this kind of two (or more) stage method means that I'm running all of my tests in the context of one test with dozens of asserts, which seems like a kind of degenerate way to use the framework, and makes bugs harder to find. Is there a way to have something like an asynchronous setup? Is there another testing framework that handles this better?

    Read the article

  • Functional languages targeting the LLVM

    - by Matthew
    Are there any languages that target the LLVM that: Are statically typed Use type inference Are functional (i.e. lambda expressions, closures, list primitives, list comprehensions, etc.) Have first class object-oriented features (inheritance, polymorphism, mixins, etc.) Have a sophisticated type system (generics, covariance and contravariance, etc.) Scala is all of these, but only targets the JVM. F# (and to some extent C#) is most if not all of these, but only targets .NET. What similar language targets the LLVM?

    Read the article

  • How does functional programming work?

    - by Headcrab
    I'm used to imperative/OO programming (know C, C++, Python, PHP, etc.). I wanted to get into functional programming but there are some things unclear to me. Take for example the languages F# and Haskell: How do you implement loops? By recursion? Eew. What about conditions? How can you get by without variables? I mean.. What do we have RAM for.. storing variables, right?

    Read the article

  • Functional languages & support for memoization

    - by Joel
    Do any of the current crop of popular functional languages have good support for memoization & if I was to pick one on the strength of its memoisation which would you recommend & why? Update: I'm looking to optimise a directed graph (where nodes could be functions or data). When a node in the graph is updated I would like the values of other nodes to be recalculated only if they depend the node that changed. Update2: require free or open-source language/runtime.

    Read the article

  • Scala, make my loop more functional

    - by Pengin
    I'm trying to reduce the extent to which I write Scala (2.8) like Java. Here's a simplification of a problem I came across. Can you suggest improvements on my solutions that are "more functional"? Transform the map val inputMap = mutable.LinkedHashMap(1->'a',2->'a',3->'b',4->'z',5->'c') by discarding any entries with value 'z' and indexing the characters as they are encountered First try var outputMap = new mutable.HashMap[Char,Int]() var counter = 0 for(kvp <- inputMap){ val character = kvp._2 if(character !='z' && !outputMap.contains(character)){ outputMap += (character -> counter) counter += 1 } } Second try (not much better, but uses an immutable map and a 'foreach') var outputMap = new immutable.HashMap[Char,Int]() var counter = 0 inputMap.foreach{ case(number,character) => { if(character !='z' && !outputMap.contains(character)){ outputMap2 += (character -> counter) counter += 1 } } }

    Read the article

  • Purely functional equivalent of weakhashmap?

    - by Jon Harrop
    Weak hash tables like Java's weak hash map use weak references to track the collection of unreachable keys by the garbage collector and remove bindings with that key from the collection. Weak hash tables are typically used to implement indirections from one vertex or edge in a graph to another because they allow the garbage collector to collect unreachable portions of the graph. Is there a purely functional equivalent of this data structure? If not, how might one be created? This seems like an interesting challenge. The internal implementation cannot be pure because it must collect (i.e. mutate) the data structure in order to remove unreachable parts but I believe it could present a pure interface to the user, who could never observe the impurities because they only affect portions of the data structure that the user can, by definition, no longer reach.

    Read the article

  • Functional equivalent of if (p(f(a), f(b)) a else b

    - by oxbow_lakes
    I'm guessing that there must be a better functional way of expressing the following: def foo(i: Any) : Int if (foo(a) < foo(b)) a else b So in this example f == foo and p == _ < _. There's bound to be some masterful cleverness in scalaz for this! I can see that using BooleanW I can write: p(f(a), f(b)).option(a).getOrElse(b) But I was sure that I would be able to write some code which only referred to a and b once. If this exists it must be on some combination of Function1W and something else but scalaz is a bit of a mystery to me! EDIT: I guess what I'm asking here is not "how do I write this?" but "What is the correct name and signature for such a function and does it have anything to do with FP stuff I do not yet understand like Kleisli, Comonad etc?"

    Read the article

  • Handling incremental Data Modeling Changes in Functional Programming

    - by Adam Gent
    Most of the problems I have to solve in my job as a developer have to do with data modeling. For example in a OOP Web Application world I often have to change the data properties that are in a object to meet new requirements. If I'm lucky I don't even need to programmatically add new "behavior" code (functions,methods). Instead I can declarative add validation and even UI options by annotating the property (Java). In Functional Programming it seems that adding new data properties requires lots of code changes because of pattern matching and data constructors (Haskell, ML). How do I minimize this problem? This seems to be a recognized problem as Xavier Leroy states nicely on page 24 of "Objects and Classes vs. Modules" - To summarize for those that don't have a PostScript viewer it basically says FP languages are better than OOP languages for adding new behavior over data objects but OOP languages are better for adding new data objects/properties. Are there any design pattern used in FP languages to help mitigate this problem? I have read Phillip Wadler's recommendation of using Monads to help this modularity problem but I'm not sure I understand how?

    Read the article

  • C# functional quicksort is failing

    - by Rubys
    I'm trying to implement quicksort in a functional style using C# using linq, and this code randomly works/doesn't work, and I can't figure out why. Important to mention: When I call this on an array or list, it works fine. But on an unknown-what-it-really-is IEnumerable, it goes insane (loses values or crashes, usually. sometimes works.) The code: public static IEnumerable<T> Quicksort<T>(this IEnumerable<T> source) where T : IComparable<T> { if (!source.Any()) yield break; var pivot = source.First(); var sortedQuery = source.Skip(1).Where(a => a.CompareTo(source.First()) <= 0).Quicksort() .Concat(new[] { pivot }) .Concat(source.Skip(1).Where(a => a.CompareTo(source.First()) > 0).Quicksort()); foreach (T key in sortedQuery) yield return key; } Can you find any faults here that would cause this to fail?

    Read the article

  • Flowcharting functional programming languages

    - by Sadface
    Flowcharting. This ancient old practice that's been in use for over 1000 years now, being forced upon us poor students, without any usefulness (or so do I think). It might work well with imperative, sequentially running languages, but what about my beloved functional programming? Sadly, I'm forced to create a flow chart for my programm (that is written in Haskell). I imagine it being easy for something like this: main :: IO () main = do someInput <- getLine let upped = map toUpper someInput putStrLn upped Which is just 3 sequenced steps, fetching data, uppercasing it, outputting it. Things look worse this time: main :: IO () main = do someInput <- fmap toUpper getLine putStrLn someInput Or like this: main :: IO () main = interact (map toUpper) Okay, that was IO, you can handle that like an imperative language. What about pure functions? An actual example: onlyMatching :: String -> [FilePath] -> [FilePath] onlyMatching ext = filter f where f name = lower ('.' : ext) == (lower . takeExtension $ name) lower = map toLower How would you flowchart that last one?

    Read the article

  • Problem with routes in functional testing

    - by Wishmaster
    Hi, I'm making a simple test project to prepare myself for my test. I'm fairly new to nested resources, in my example I have a newsitem and each newsitem has comments. The routing looks like this: resources :comments resources :newsitems do resources :comments end I'm setting up the functional tests for comments at the moment and I ran into some problems. This will get the index of the comments of a newsitem. @newsitem is declared in the setup ofc. test "should get index" do get :index,:newsitem_id => @newsitem assert_response :success assert_not_nil assigns(:newsitem) end But the problem lays here, in the "should get new". test "should get new" do get new_newsitem_comment_path(@newsitem) assert_response :success end I'm getting the following error. ActionController::RoutingError: No route matches {:controller=>"comments", :action=>"/newsitems/1/comments/new"} But when I look into the routes table, I see this: new_newsitem_comment GET /newsitems/:newsitem_id/comments/new(.:format) {:action=>"new", :controller=>"comments"} Can't I use the name path or what I'm doing wrong here? Thanks in advance.

    Read the article

  • What is a Non-Functional Requirement?

    - by atconway
    In my breakdown of work I have to define work against 'Functional' and 'Non-Functional' design elements / work in my applications. I read the description from Wikipedia here: https://en.wikipedia.org/wiki/Non-functional_requirement but as typical the description did not speak exactly to me to clear up my understanding. Can someone please explain in terms of an example when creating an application from scratch, what would be defined as a 'Non-Functional' requirement?

    Read the article

  • Functional vs. Non-Functional Requirements vs Design ideas in an SRS

    - by Nicholas Chow
    For a school project, I had to create a SRS for a "fictional" application. However they did not show us what it exactly entails, and were very vague with explanations. The SRS asked of us has to have at least 5 functional requirements, 5 non functional requirements and 1 constraint. Now I have tried my best to make one however I there are still some uncertainties left, I hope you experts can tell me whether or not I am thinking in the right direction. I will keep on updating this posts as I have questions regarding requirements that are vague to me, thank you all in advance for making SRS more clear for me FR1 Registration of Organizer FR1 describes the registration of an Organizer on CrowdFundum FR1.1 The system shall display a registration form on the website. FR1.2 The system shall require a Name, Username, Document number passport/ID card, Address, Zip code, City, Email address, Telephone number, Bank account, Captcha code on the registration form when a user registers. FR1.3 The system shall check whether the Name, Username, Document number passport/ID card, Address, Zip code, City, Email address, Telephone number, Bank account, Captcha code are filled out correctly within 1 seconds after a user submits the registration form. FR1.4 The system shall display an error message containing: “Registration could not be completed” to the subscriber within 1 seconds after the system check of the registration form was unsuccessful. FR1.5 The system shall send a verification email containing a verification link to the subscriber within 30 seconds after the system check of the registration form was successful. FR1.6 The system shall add the newly registered Organizer to the user base within 5 seconds after the verification link was accessed. Questions: FR1.1 Is this a functional requirement, or have I incorporated design idea in it by using "shall display on website". If so what would be a better way to write it? FR1.2 Is this better written in one requirement, or should I write each condition as a seperate requirement? FR1.3-1.5 Are these functional requirements or did I mix some non functional elements in it? How is it better phrased? FR1.3-1.6 Are these all correct functional requirements? As in free of ambiguity, complete, implementation free etc.

    Read the article

  • Efficiency of purely functional programming

    - by Sid
    Does anyone know what is the worst possible asymptotic slowdown that can happen when programming purely functionally as opposed to imperatively (i.e. allowing side-effects)? Clarification from comment by itowlson: is there any problem for which the best known non-destructive algorithm is asymptotically worse than the best known destructive algorithm, and if so by how much?

    Read the article

  • Debugging F# code and functional style

    - by Roger Alsing
    I'm new to funcctional programming and have some questions regarding coding style and debugging. I'm under the impression that one should avoid storing results from funcction calls in a temp variable and then return that variable e.g. let someFunc foo = let result = match foo with | x -> ... | y -> ... result And instead do it like this (I might be way off?): let someFunc foo = match foo with | x -> ... | y -> ... Which works fine from a functionallity perspective, but it makes it way harder to debug. I have no way to examine the result if the right hand side of - does some funky stuff. So how should I deal with this kind of scenarios?

    Read the article

  • Database Functional Programming in Clojure

    - by Ralph
    "It is tempting, if the only tool you have is a hammer, to treat everything as if it were a nail." - Abraham Maslow I need to write a tool to dump a large hierarchical (SQL) database to XML. The hierarchy consists of a Person table with subsidiary Address, Phone, etc. tables. I have to dump thousands of rows, so I would like to do so incrementally and not keep the whole XML file in memory. I would like to isolate non-pure function code to a small portion of the application. I am thinking that this might be a good opportunity to explore FP and concurrency in Clojure. I can also show the benefits of immutable data and multi-core utilization to my skeptical co-workers. I'm not sure how the overall architecture of the application should be. I am thinking that I can use an impure function to retrieve the database rows and return a lazy sequence that can then be processed by a pure function that returns an XML fragment. For each Person row, I can create a Future and have several processed in parallel (the output order does not matter). As each Person is processed, the task will retrieve the appropriate rows from the Address, Phone, etc. tables and generate the nested XML. I can use a a generic function to process most of the tables, relying on database meta-data to get the column information, with special functions for the few tables that need custom processing. These functions could be listed in a map(table name -> function). Am I going about this in the right way? I can easily fall back to doing it in OO using Java, but that would be no fun. BTW, are there any good books on FP patterns or architecture? I have several good books on Clojure, Scala, and F#, but although each covers the language well, none look at the "big picture" of function programming design.

    Read the article

  • Persistent (purely functional) Red-Black trees on disk performance

    - by Waneck
    I'm studying the best data structures to implement a simple open-source object temporal database, and currently I'm very fond of using Persistent Red-Black trees to do it. My main reasons for using persistent data structures is first of all to minimize the use of locks, so the database can be as parallel as possible. Also it will be easier to implement ACID transactions and even being able to abstract the database to work in parallel on a cluster of some kind. The great thing of this approach is that it makes possible implementing temporal databases almost for free. And this is something quite nice to have, specially for web and for data analysis (e.g. trends). All of this is very cool, but I'm a little suspicious about the overall performance of using a persistent data structure on disk. Even though there are some very fast disks available today, and all writes can be done asynchronously, so a response is always immediate, I don't want to build all application under a false premise, only to realize it isn't really a good way to do it. Here's my line of thought: - Since all writes are done asynchronously, and using a persistent data structure will enable not to invalidate the previous - and currently valid - structure, the write time isn't really a bottleneck. - There are some literature on structures like this that are exactly for disk usage. But it seems to me that these techniques will add more read overhead to achieve faster writes. But I think that exactly the opposite is preferable. Also many of these techniques really do end up with a multi-versioned trees, but they aren't strictly immutable, which is something very crucial to justify the persistent overhead. - I know there still will have to be some kind of locking when appending values to the database, and I also know there should be a good garbage collecting logic if not all versions are to be maintained (otherwise the file size will surely rise dramatically). Also a delta compression system could be thought about. - Of all search trees structures, I really think Red-Blacks are the most close to what I need, since they offer the least number of rotations. But there are some possible pitfalls along the way: - Asynchronous writes -could- affect applications that need the data in real time. But I don't think that is the case with web applications, most of the time. Also when real-time data is needed, another solutions could be devised, like a check-in/check-out system of specific data that will need to be worked on a more real-time manner. - Also they could lead to some commit conflicts, though I fail to think of a good example of when it could happen. Also commit conflicts can occur in normal RDBMS, if two threads are working with the same data, right? - The overhead of having an immutable interface like this will grow exponentially and everything is doomed to fail soon, so this all is a bad idea. Any thoughts? Thanks! edit: There seems to be a misunderstanding of what a persistent data structure is: http://en.wikipedia.org/wiki/Persistent_data_structure

    Read the article

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