Search Results

Search found 762 results on 31 pages for 'haskell'.

Page 15/31 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • How do you solve this Haskell problem using a fold map and take?

    - by Linda Cohen
    Define a function replicate which given a list of numbers returns a list with each number duplicated its value. Use a fold, map, and take .. replicate [5,1,3,2,8,1,2] output: [5,5,5,5,5,1,3,3,3,2,2,8,8,8,8,8,8,8,8,1,2,2] I've figure this out using List comprehension and recursion: replicate2 [] = [] replicate2 (n:nn) = take n(repeat n) ++ replicate2 nn but how would you use fold and map to do this? so far I have: replicate n = map (foldl1 (take n(repeat n)) n) n which is obviously wrong, but I think I am close.. so any help would be nice, THANKS!

    Read the article

  • Haskell: "how much" of a type should functions receive? and avoiding complete "reconstruction"

    - by L01man
    I've got these data types: data PointPlus = PointPlus { coords :: Point , velocity :: Vector } deriving (Eq) data BodyGeo = BodyGeo { pointPlus :: PointPlus , size :: Point } deriving (Eq) data Body = Body { geo :: BodyGeo , pict :: Color } deriving (Eq) It's the base datatype for characters, enemies, objects, etc. in my game (well, I just have two rectangles as the player and the ground right now :p). When a key, the characters moves right, left or jumps by changing its velocity. Moving is done by adding the velocity to the coords. Currently, it's written as follows: move (PointPlus (x, y) (xi, yi)) = PointPlus (x + xi, y + yi) (xi, yi) I'm just taking the PointPlus part of my Body and not the entire Body, otherwise it would be: move (Body (BodyGeo (PointPlus (x, y) (xi, yi)) wh) col) = (Body (BodyGeo (PointPlus (x + xi, y + yi) (xi, yi)) wh) col) Is the first version of move better? Anyway, if move only changes PointPlus, there must be another function that calls it inside a new Body. I explain: there's a function update which is called to update the game state; it is passed the current game state, a single Body for now, and returns the updated Body. update (Body (BodyGeo (PointPlus xy (xi, yi)) wh) pict) = (Body (BodyGeo (move (PointPlus xy (xi, yi))) wh) pict) That tickles me. Everything is kept the same within Body except the PointPlus. Is there a way to avoid this complete "reconstruction" by hand? Like in: update body = backInBody $ move $ pointPlus body Without having to define backInBody, of course.

    Read the article

  • Applying a function with multiple inputs using Map? (Haskell)

    - by Schroedinger
    G'day guys, Trying currently to finish up a bit of homework I'm working on, and having an issue where I'm trying to apply map across a function that accepts multiple inputs. so in the case I'm using processList f (x:xs) = map accelerateList f xs x xs processList is given a floating value (f) and a List that it sorts into another List Accelerate List takes a floating value (f) a List and a List Object through which it returns another List Object I know my Accelerate List code is correct, but I cannot for the life of me get the syntax for this code working: processList :: Float -> [Object] -> [Object] accelerate f [] = [] accelerate f [x] = [(accelerateForce f x x)] accelerate f (x:xs) = map accelerateList f xs x xs Any ideas? I've been scratching my head for about 3 hours now. I know it's something really simple.

    Read the article

  • Haskell. Numbers in binary numbers. words

    - by Katja
    Hi! I need to code words into binary numbers. IN: "BCD..." OUT:1011... I have written already funktion for coding characters into siple numbers IN: 'C' OUT: 3 IN: 'c' OUT: 3 lett2num :: Char -> Int lett2num x | (ord 'A' <= ord x) && (ord x <= ord 'Z') = (ord x - ord 'A') + 1 | (ord 'a' <= ord x) && (ord x <= ord 'z') = (ord x - ord 'a') +1 num2lett :: Int -> Char num2lett n | (n <= ord 'A') && (n <= ord 'Z') = chr(ord 'A'+ n - 1) | (n <= ord 'a') && (n <= ord 'Z') = chr(ord 'A'+ n - 1) I wrote as well function for codind simple numbers into binary. num2bin :: Int->[Int] num2bin 0 = [] num2bin n | n>=0 = n `mod` 2 : (num2bin( n `div` 2)) | otherwise = error but I donw want those binary numbers to be in a list how can I get rid of the lists? Thanks

    Read the article

  • Good functions and techniques for dealing with haskell tuples?

    - by toofarsideways
    I've been doing a lot of work with tuples and lists of tuples recently and I've been wondering if I'm being sensible. Things feel awkward and clunky which for me signals that I'm doing something wrong. For example I've written three convenience functions for getting the first, second and third value in a tuple of 3 values. Is there a better way I'm missing? Are there more general functions that allow you to compose and manipulate tuple data? Here are some things I am trying to do that feel should be generalisable. Extracting values: Do I need to create a version of fst,snd,etc... for tuples of size two, three, four and five, etc...? fst3(x,_,_) = x fst4(x,_,_,_) = x Manipulating values: Can you increment the last value in a list of pairs and then use that same function to increment the last value in a list of triples? Zipping and Unzipping values: There is a zip and a zip3. Do I also need a zip4? or is there some way of creating a general zip function? Sorry if this seems subjective, I honestly don't know if this is even possible or if I'm wasting my time writing 3 extra functions every time I need a general solution. Thank you for any help you can give!

    Read the article

  • Haskell: How to compose `not` with a function of arbitrary arity?

    - by Hynek -Pichi- Vychodil
    When I have some function of type like f :: (Ord a) => a -> a -> Bool f a b = a > b I should like make function which wrap this function with not. e.g. make function like this g :: (Ord a) => a -> a -> Bool g a b = not $ f a b I can make combinator like n f = (\a -> \b -> not $ f a b) But I don't know how. *Main> let n f = (\a -> \b -> not $ f a b) n :: (t -> t1 -> Bool) -> t -> t1 -> Bool Main> :t n f n f :: (Ord t) => t -> t -> Bool *Main> let g = n f g :: () -> () -> Bool What am I doing wrong? And bonus question how I can do this for function with more and lest parameters e.g. t -> Bool t -> t1 -> Bool t -> t1 -> t2 -> Bool t -> t1 -> t2 -> t3 -> Bool

    Read the article

  • How to see if type is instance of a class in Haskell?

    - by Raekye
    I'm probably doing this completely wrong (the unhaskell way); I'm just learning so please let me know if there's a better way to approach this. Context: I'm writing a bunch of tree structures. I want to reuse my prettyprint function for binary trees. Not all trees can use the generic Node/Branch data type though; different trees need different extra data. So to reuse the prettyprint function I thought of creating a class different trees would be instances of: class GenericBinaryTree a where is_leaf :: a -> Bool left :: a -> a node :: a -> b right :: a -> a This way they only have to implement methods to retrieve the left, right, and current node value, and prettyprint doesn't need to know about the internal structure. Then I get down to here: prettyprint_helper :: GenericBinaryTree a => a -> [String] prettyprint_helper tree | is_leaf tree = [] | otherwise = ("{" ++ (show (node tree)) ++ "}") : (prettyprint_subtree (left tree) (right tree)) where prettyprint_subtree left right = ((pad "+- " "| ") (prettyprint_helper right)) ++ ((pad "`- " " ") (prettyprint_helper left)) pad first rest = zipWith (++) (first : repeat rest) And I get the Ambiguous type variable 'a0' in the constraint: (Show a0) arising from a use of 'show' error for (show (node tree)) Here's an example of the most basic tree data type and instance definition (my other trees have other fields but they're irrelevant to the generic prettyprint function) data Tree a = Branch (Tree a) a (Tree a) | Leaf instance GenericBinaryTree (Tree a) where is_leaf Leaf = True is_leaf _ = False left (Branch left node right) = left right (Branch left node right) = right node (Branch left node right) = node I could have defined node :: a -> [String] and deal with the stringification in each instance/type of tree, but this feels neater. In terms of prettyprint, I only need a string representation, but if I add other generic binary tree functions later I may want the actual values. So how can I write this to work whether the node value is an instance of Show or not? Or what other way should I be approaching this problem? In an object oriented language I could easily check whether a class implements something, or if an object has a method. I can't use something like prettyprint :: Show a => a -> String Because it's not the tree that needs to be showable, it's the value inside the tree (returned by function node) that needs to be showable. I also tried changing node to Show b => a -> b without luck (and a bunch of other type class/preconditions/whatever/I don't even know what I'm doing anymore).

    Read the article

  • Basis of definitions

    - by Yttrill
    Let us suppose we have a set of functions which characterise something: in the OO world methods characterising a type. In mathematics these are propositions and we have two kinds: axioms and lemmas. Axioms are assumptions, lemmas are easily derived from them. In C++ axioms are pure virtual functions. Here's the problem: there's more than one way to axiomatise a system. Given a set of propositions or methods, a subset of the propositions which is necessary and sufficient to derive all the others is called a basis. So too, for methods or functions, we have a desired set which must be defined, and typically every one has one or more definitions in terms of the others, and we require the programmer to provide instance definitions which are sufficient to allow all the others to be defined, and, if there is an overspecification, then it is consistent. Let me give an example (in Felix, Haskell code would be similar): class Eq[t] { virtual fun ==(x:t,y:t):bool => eq(x,y); virtual fun eq(x:t, y:t)=> x == y; virtual fun != (x:t,y:t):bool => not (x == y); axiom reflex(x:t): x == x; axiom sym(x:t, y:t): (x == y) == (y == x); axiom trans(x:t, y:t, z:t): implies(x == y and y == z, x == z); } Here it is clear: the programmer must define either == or eq or both. If both are defined, the definitions must be equivalent. Failing to define one doesn't cause a compiler error, it causes an infinite loop at run time. Defining both inequivalently doesn't cause an error either, it is just inconsistent. Note the axioms specified constrain the semantics of any definition. Given a definition of == either directly or via a definition of eq, then != is defined automatically, although the programmer might replace the default with something more efficient, clearly such an overspecification has to be consistent. Please note, == could also be defined in terms of !=, but we didn't do that. A characterisation of a partial or total order is more complex. It is much more demanding since there is a combinatorial explosion of possible bases. There is an reason to desire overspecification: performance. There also another reason: choice and convenience. So here, there are several questions: one is how to check semantics are obeyed and I am not looking for an answer here (way too hard!). The other question is: How can we specify, and check, that an instance provides at least a basis? And a much harder question: how can we provide several default definitions which depend on the basis chosen?

    Read the article

  • Lazy Processing of Streams

    - by Giorgio
    I have the following problem scenario: I have a text file and I have to read it and split it into lines. Some lines might need to be dropped (according to criteria that are not fixed). The lines that are not dropped must be parsed into some predefined records. Records that are not valid must be dropped. Duplicate records may exist and, in such a case, they are consecutive. If duplicate / multiple records exist, only one item should be kept. The remaining records should be grouped according to the value contained in one field; all records belonging to the same group appear one after another (e.g. AAAABBBBCCDEEEFF and so on). The records of each group should be numbered (1, 2, 3, 4, ...). For each group the numbering starts from 1. The records must then be saved somewhere / consumed in the same order as they were produced. I have to implement this in Java or C++. My first idea was to define functions / methods like: One method to get all the lines from the file. One method to filter out the unwanted lines. One method to parse the filtered lines into valid records. One method to remove duplicate records. One method to group records and number them. The problem is that the data I am going to read can be too big and might not fit into main memory: so I cannot just construct all these lists and apply my functions one after the other. On the other hand, I think I do not need to fit all the data in main memory at once because once a record has been consumed all its underlying data (basically the lines of text between the previous record and the current record, and the record itself) can be disposed of. With the little knowledge I have of Haskell I have immediately thought about some kind of lazy evaluation, in which instead of applying functions to lists that have been completely computed, I have different streams of data that are built on top of each other and, at each moment, only the needed portion of each stream is materialized in main memory. But I have to implement this in Java or C++. So my question is which design pattern or other technique can allow me to implement this lazy processing of streams in one of these languages.

    Read the article

  • How do I organize a GUI application for passing around events and for setting up reads from a shared resource

    - by Savanni D'Gerinel
    My tools involved here are GTK and Haskell. My questions are probably pretty trivial for anyone who has done significant GUI work, but I've been off in the equivalent of CGI applications for my whole career. I'm building an application that displays tabular data, displays the same data in a graph form, and has an edit field for both entering new data and for editing existing data. After asking about sharing resources, I decided that all of the data involved will be stored in an MVar so that every component can just read the current state from the MVar. All of that works, but now it is time for me to rearrange the application so that it can be interactive. With that in mind, I have three widgets: a TextView (for editing), a TreeView (for displaying the data), and a DrawingArea (for displaying the data as a graph). I THINK I need to do two things, and the core of my question is, are these the right things, or is there a better way. Thing the first: All event handlers, those functions that will be called any time a redisplay is needed, need to be written at a high level and then passed into the function that actually constructs the widget to begin with. For instance: drawStatData :: DrawingArea -> MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO () createStatView :: (DrawingArea -> IO ()) -> IO VBox createUI :: MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO HBox createUI storeMVar field = do graphs <- createStatView (\area -> drawStatData area storeMVar field) hbox <- hBoxNew False 10 boxPackStart hbox graphs PackNatural 0 return hbox In this case, createStatView builds up a VBox that contains a DrawingArea to graph the data and potentially other widgets. It attaches drawStatData to the realize and exposeEvent events for the DrawingArea. I would do something similar for the TreeView, but I am not completely sure what since I have not yet done it and what I am thinking of would involve replacing the TreeModel every time the TreeView needs to be updated. My alternative to the above would be... drawStatData :: DrawingArea -> MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO () createStatView :: IO (VBox, DrawingArea) ... but in this case, I would arrange createUI like so: createUI :: MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO HBox createUI storeMVar field = do (graphbox, graph) <- createStatView (\area -> drawStatData area storeMVar field) hbox <- hBoxNew False 10 boxPackStart hbox graphs PackNatural 0 on graph realize (drawStatData graph storeMVar field) on graph exposeEvent (do liftIO $ drawStatData graph storeMVar field return ()) return hbox I'm not sure which is better, but that does lead me to... Thing the second: it will be necessary for me to rig up an event system so that various events can send signals all the way to my widgets. I'm going to need a mediator of some kind to pass events around and to translate application-semantic events to the actual events that my widgets respond to. Is it better for me to pass my addressable widgets up the call stack to the level where the mediator lives, or to pass the mediator down the call stack and have the widgets register directly with it? So, in summary, my two questions: 1) pass widgets up the call stack to a global mediator, or pass the global mediator down and have the widgets register themselves to it? 2) pass my redraw functions to the builders and have the builders attach the redraw functions to the constructed widgets, or pass the constructed widgets back and have a higher level attach the redraw functions (and potentially link some widgets together)? Okay, and... 3) Books or wikis about GUI application architecture, preferably coherent architectures where people aren't arguing about minute details? The application in its current form (displays data but does not write data or allow for much interaction) is available at https://bitbucket.org/savannidgerinel/fitness . You can run the application by going to the root directory and typing runhaskell -isrc src/Main.hs data/ or... cabal build dist/build/fitness/fitness data/ You may need to install libraries, but cabal should tell you which ones.

    Read the article

  • How do I get Mathematica to thread a 2-variable function over two lists, using functional programmin

    - by Leah Wrenn Berman
    Lets say I have a function f[x_, y_], and two lists l1, l2. I'd like to evaluate f[x,y] where x runs over the list l1 and y runs over the list l2, and I'd like to do it without having to make all pairs of the form {l1[[i]],l2[[j]]}. (Motivation: I'm trying to implement some basic Haskell programs in Mathematica. In particular, I'd like to be able to code the Haskell program isMatroid::[[Int]]->Bool isMatroid b =and[or[sort(union(xs\\[x])[y]'elem'b|y<-ys]|xs<-b,ys<-b, xs<-x] I think I can do the rest of it, if I can figure out the original question, but I'd like the code to be Haskell-like. Any suggestions for implementing Haskell-like code in Mathematica would be appreciated.)

    Read the article

  • Resources for improving your comprehension of recursion?

    - by Andrew M
    I know what recursion is (when a patten reoccurs within itself, typically a function that calls itself on one of its lines, after a breakout conditional... right?), and I can understand recursive functions if I study them closely. My problem is, when I see new examples, I'm always initially confused. If I see a loop, or a mapping, zipping, nesting, polymorphic calling, and so on, I know what's going just by looking at it. When I see recursive code, my thought process is usually 'wtf is this?' followed by 'oh it's recursive' followed by 'I guess it must work, if they say it does.' So do you have any tips/plans/resources for building up your skills in this area? Recursion is kind of a wierd concept so I'm thinking the way to tackle it may be equally wierd and inobvious.

    Read the article

  • Problem with creating a deterministic finite automata (DFA) - Mercury

    - by Jabba The hut
    I would like to have a deterministic finite automata (DFA) simulated in Mercury. But I’m s(t)uck at several places. Formally, a DFA is described with the following characteristics: a setOfStates S, an inputAlphabet E <-- summation symbol, a transitionFunction : S × E -- S, a startState s € S, a setOfAcceptableFinalStates F =C S. A DFA will always starts in the start state. Then the DFA will read all the characters on the input, one by one. Based on the current input character and the current state, there will be made to a new state. These transitions are defined in the transitions function. when the DFA is in one of his acceptable final states, after reading the last character, then will the DFA accept the input, If not, then the input will be is rejected. The figure shows a DFA the accepting strings where the amount of zeros, is a plurality of three. Condition 1 is the initial state, and also the only acceptable state. for each input character is the corresponding arc followed to the next state. Link to Figure What must be done A type “mystate” which represents a state. Each state has a number which is used for identification. A type “transition” that represents a possible transition between states. Each transition has a source_state, an input_character, and a final_state. A type “statemachine” that represents the entire DFA. In the solution, the DFA must have the following properties: The set of all states, the input alphabet, a transition function, represented as a set of possible transitions, a set of accepting final states, a current state of the DFA A predicate “init_machine (state machine :: out)” which unifies his arguments with the DFA, as shown as in the Figure. The current state for the DFA is set to his initial state, namely, 1. The input alphabet of the DFA is composed of the characters '0'and '1'. A user can enter a text, which will be controlled by the DFA. the program will continues until the user types Ctrl-D and simulates an EOF. If the user use characters that are not allowed into the input alphabet of the DFA, then there will be an error message end the program will close. (pred require) Example Enter a sentence: 0110 String is not ok! Enter a sentence: 011101 String is not ok! Enter a sentence: 110100 String is ok! Enter a sentence: 000110010 String is ok! Enter a sentence: 011102 Uncaught exception Mercury: Software Error: Character does not belong to the input alphabet! the thing wat I have. :- module dfa. :- interface. :- import_module io. :- pred main(io.state::di, io.state::uo) is det. :- implementation. :- import_module int,string,list,bool. 1 :- type mystate ---> state(int). 2 :- type transition ---> trans(source_state::mystate, input_character::bool, final_state::mystate). 3 (error, finale_state and current_state and input_character) :- type statemachine ---> dfa(list(mystate),list(input_character),list(transition),list(final_state),current_state(mystate)) 4 missing a lot :- pred init_machine(statemachine :: out) is det. %init_machine(statemachine(L_Mystate,0,L_transition,L_final_state,1)) :- <-probably fault 5 not perfect main(!IO) :- io.write_string("\nEnter a sentence: ", !IO), io.read_line_as_string(Input, !IO), ( Invoer = ok(StringVar), S1 = string.strip(StringVar), (if S1 = "mustbeabool" then io.write_string("Sentenceis Ok! ", !IO) else io.write_string("Sentence is not Ok!.", !IO)), main(!IO) ; Invoer = eof ; Invoer = error(ErrorCode), io.format("%s\n", [s(io.error_message(ErrorCode))], !IO) ). Hope you can help me kind regards

    Read the article

  • What is this algorithm for converting strings into numbers called?

    - by CodexArcanum
    I've been doing some work in Parsec recently, and for my toy language I wanted multi-based fractional numbers to be expressible. After digging around in Parsec's source a bit, I found their implementation of a floating-point number parser, and copied it to make the needed modifications. So I understand what this code does, and vaguely why (I haven't worked out the math fully yet, but I think I get the gist). But where did it come from? This seems like a pretty clever way to turn strings into floats and ints, is there a name for this algorithm? Or is it just something basic that's a hole in my knowledge? Did the folks behind Parsec devise it? Here's the code, first for integers: number' :: Integer -> Parser Integer number' base = do { digits <- many1 ( oneOf ( sigilRange base )) ; let n = foldl (\x d -> base * x + toInteger (convertDigit base d)) 0 digits ; seq n (return n) } So the basic idea here is that digits contains the string representing the whole number part, ie "192". The foldl converts each digit individually into a number, then adds that to the running total multiplied by the base, which means that by the end each digit has been multiplied by the correct factor (in aggregate) to position it. The fractional part is even more interesting: fraction' :: Integer -> Parser Double fraction' base = do { digits <- many1 ( oneOf ( sigilRange base )) ; let base' = fromIntegral base ; let f = foldr (\d x -> (x + fromIntegral (convertDigit base d))/base') 0.0 digits ; seq f (return f) Same general idea, but now a foldr and using repeated division. I don't quite understand why you add first and then divide for the fraction, but multiply first then add for the whole. I know it works, just haven't sorted out why. Anyway, I feel dumb not working it out myself, it's very simple and clever looking at it. Is there a name for this algorithm? Maybe the imperative version using a loop would be more familiar?

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >