I was trying to recursively pass a function to itself a given number of times. So given the input in form of Function | RepeatNumber(Count) | Argument. So as an example if given the input: f 3 2 it would return f(f(f 2) This should then also work if the Function value where "square" it would Square the argument.
In terms of the logic I approached it as follows:
def repeatnew func count arg
if count == 1 then (func arg)
else (func (repeatnew func (count -1) arg))
I've been trying to research a solution to this for a while and I came across using Iterate and some other functions. Finally I came across this: https://wiki.haskell.org/Higher_order_function However I was unable to implement a working solution.
Edit: The solutions I did try to implement I could get compiling correctly, I am still very inexperienced with haskell and would appreciate an explanation on how to create a higher order function using my parameters.
Spinning off from #Antisthenes' comment, One other way to do this is using the foldl1 with no base case.
pipeNTimes :: (a -> a) -> Int -> (a -> a)
pipeNTimes f n = foldl1 (.) $ replicate n f
pipeNTimes (*2) 3 2 -- returns 16
I am admittedly only a beginner at Haskell, so this may be a naive implementation, but I think this does what you are looking for:
applyRecursively f x y
| x == 1 = f y
| otherwise = f (applyRecursively f (x-1) y)
The applyRecursively function takes a function and two numbers as arguments.
If the middle argument (the count) is 1 then we apply the parameter function to the argument y. This is the edge case that stops the recursion.
The otherwise guard clause then calls recursively with the x parameter decremented, and applies function f to the result.
I have tested it using a lambda like this:
applyRecursively (\x -> x + 1) 3 3
It should add 1 to the values of 3 three times - it returns a value of 6 so it looks like it works.
As I say, I'm a beginner but I think this does what you're looking for.
Related
I need your help guys.
Im trying to learn and do a simple task in haskell, but it's still hard for me.
What im trying to do is: Read a line of numbers separated with whitespace, iterate over that list, check values, and if values are not zero add 1 otherwise -1. I was trying to do it watching some tutorials and other project code, but it just outputs a bunch of errors.
My code:
import System.Environment
import Control.Monad
import Text.Printf
import Data.List
import System.IO
solve :: IO ()
solve = do
nums <- map read . words <$> getLine
print (calculate nums)
calculate (x:xs) = x + check xs
check num
| num == 0 =
-1
| otherwise =
1
main :: IO ()
main = do
n <- readLn
if n /= 0
then do
printf "Case: "
solve
else main
Errors:
C:\Users\Donatas\Documents\haskell\la3.hs:9:21: error:
* Ambiguous type variable `b0' arising from a use of `read'
prevents the constraint `(Read b0)' from being solved.
Probable fix: use a type annotation to specify what `b0' should be.
These potential instances exist:
instance Read BufferMode -- Defined in `GHC.IO.Handle.Types'
instance Read Newline -- Defined in `GHC.IO.Handle.Types'
instance Read NewlineMode -- Defined in `GHC.IO.Handle.Types'
...plus 25 others
...plus six instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
* In the first argument of `map', namely `read'
In the first argument of `(.)', namely `map read'
In the first argument of `(<$>)', namely `map read . words'
|
9 | nums <- map read . words <$> getLine
| ^^^^
C:\Users\Donatas\Documents\haskell\la3.hs:10:9: error:
* Ambiguous type variable `a0' arising from a use of `print'
prevents the constraint `(Show a0)' from being solved.
Probable fix: use a type annotation to specify what `a0' should be.
These potential instances exist:
instance Show HandlePosn -- Defined in `GHC.IO.Handle'
instance Show BufferMode -- Defined in `GHC.IO.Handle.Types'
instance Show Handle -- Defined in `GHC.IO.Handle.Types'
...plus 27 others
...plus 13 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
* In a stmt of a 'do' block: print (calculate nums)
In the expression:
do nums <- map read . words <$> getLine
print (calculate nums)
In an equation for `solve':
solve
= do nums <- map read . words <$> getLine
print (calculate nums)
|
10 | print (calculate nums)
| ^^^^^^^^^^^^^^^^^^^^^^
C:\Users\Donatas\Documents\haskell\la3.hs:12:1: error:
* Non type-variable argument in the constraint: Num [a]
(Use FlexibleContexts to permit this)
* When checking the inferred type
calculate :: forall a. (Eq a, Num [a], Num a) => [a] -> a
|
12 | calculate (x:xs) = x + check xs
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Failed, no modules loaded.
To start with, I suggest you default to always writing type annotations. And before you start implementing anything, sketch out what the types of your program look like. For this program I suggest you start from:
main :: IO ()
solve :: String -> String
calculate :: [Int] -> Int
check :: Int -> Int
The names could also probably be improved to better convey what it is they're doing.
Note that there is only one function with type IO _. This serves to isolate the impure part of your program, which will make your life easier (e.g. testing, code reasoning, etc).
You're not far off. Just try reworking your code to fit into the above types. And be aware that you're missing a pattern in your calculate implementation ;)
If you inspect your code and follow the types, it is crystal-clear where the error is. Yes, you can add type annotations -- that is highly recommended -- but I find your code is so simple you could get away with just a bit of equational reasoning.
It starts with solve, it is easy to see that nums is of type Read a => [a], given that you split a string by words (i.e. [String]) and map read over it. So a list of as is what you give to calculate. As you know, a list is the disjoint sum between (1) the empty list ([]) and (2) a cons cell made of a head, an element of type a, and a tail, the rest of the list ((x:xs)).
First thing you notice is that the case of the empty list is missing; let's add it:
calculate [] = 0 -- I assume this is correct
On to the body of calculate and check. The latter clearly expects a number, you can be a bit more concise by the way:
check 0 = -1
check _ = 1
Now if you look at calculate, you see that you are calling check and passing it xs. What is xs? It is bound in the pattern (x:xs) which is how you uncons a cons cell. Clearly, xs is the tail of the cell and so a list itself. But check expects a number! The only number you can expect here is x, not xs. So let's change you code to
calculate (x:xs) = check x + ...
Your specifications state that you want to iterate over the list. That can only happen if you do something with xs. What can you do with it? The only answer to that is to call calculate recursively:
calculate (x:xs) = check x + calculate xs
... and with these changes, your code is fine.
Hi i am quite new to lua and i need to sort an Array in Lua.
So i have following code
local distances = {2,3,1}
table.sort(distances)
now i get
distances[1] -> 1
distances[2] -> 2
distances[3] -> 3
now i need to save some information for my "distances" aswell
something like the following
local distances = {{C1,2},{C2,3},{C3,1}}
now it is impossible to call the sort-function, but i need them sorted.
Is it possible to reach this?
distances[1] -> {C3,1}
distances[2] -> {C2,2}
distances[3] -> {C1,3}
Thanks guys :)
table.sort takes a comparison function as its second argument.
table.sort(distances, function (left, right)
return left[2] < right[2]
end)
I am trying to do all combinations of an Array in Ocaml.
I am trying to do a recursive function that recives an array and its initial state need to be let a = [|0;0;0|] and i need to change it recursivly like in the first iteration needs to be a = [|1;0;0|] and the next one a = [|0;1;0|] and so on until it reaches a = [|1;1;1|] making all the possible combinations, so in this case needs to do 2^3 changes.
I know that im not been very explicit but its a bit hard to me to explain, but if someone could help me i would be grateful.
An array is a mutable data structure, so if you're going to mutate it in every recursive call, then the mutation will be taken in place. Basically, it means, that after 2^3 calls, the state of array will be the last combination. So, there is no point in doing this at all. A valid solution would be to create a function, that will take an initial array, and will return a list of all combinations. An even more efficient solution is to write a function, that will take another function, and applies it to all combinations (or fold over all combinations). This will allow you to save memory, as you don't need to store all the combinations.
The outline would be to implement the following interface:
type state
val zero : state
val next : state -> state option
val value : state -> int array
Where state will be a cursor, that will move through the space of combinations. It can be an integer or an integer array, or anything else. Once these functions are implemented you can easily implement your function as follows:
let fold_combinations f init =
let rec fold state x =
let x = f (value state) x in
match next state with
| None -> x
| Some state -> fold state x in
fold zero init
Finally, your example shows not all possible combinations or permutations, but all possible binary values of bit width equal to the length of the input array. If this is really a task that you're trying to solve, then you can just translate an integer into a binary representation. In that case, the good choice for the state would be int, and then next function is an increment, that will stop at 2^k-1, where k is the length of the initial state. And the value function will just translate an integer into the array of bits, where the n-th bit (element) can be determined as state land (1 lsl n). You can use Array.init to create a fresh new array every time, alternatively, you can just iterate over the existing array. This will be more efficient, but error-prone.
let combinaison f n =
let rec aux acc n =
if n=0 then List.iter f acc
else (
aux (List.map (fun l -> 0::l ) acc) (n-1);
aux (List.map (fun l -> 1::l ) acc) (n-1);
)
in
aux [[]] n
;;
Test
combinaison ( fun lx ->
let a=Array.of_list lx in
Array.iter ( fun x ->
Printf.printf "%d " x
) a ;
Printf.printf "\n"
) 3;;
0 0 0
1 0 0
0 1 0
1 1 0
0 0 1
1 0 1
0 1 1
1 1 1
i just started with Haskell and wanted to do a little function that takes an integer and a String to repeat each char in the String as often as the integer implies.
e.g.: multiply 3 "hello" would output "hhheeelllooo"
My problem now is that i am not sure how to iterate over all the chars.
multiply::Int->String->String
multiply 1 s = s
multiply i s = multiply (i-1) (take 1 s ++ s)
so what i would get is "hhhello". so basically i need to do something like:
mult::Int->String->String
mult 0 s = []
mult 1 s = s
mult i s = "iterate over s, take each char and call a modified version of the multiply method that only takes chars above"
Thank you for helping me out
This gets easier when you use the standard library. First off, repeating an item is done with replicate:
Prelude> replicate 3 'h'
"hhh"
You can then partially apply this function and map it over the string:
Prelude> map (replicate 3) "hello"
["hhh", "eee", "lll", "lll", "ooo"]
And finally concat that list of strings into one string:
Prelude> concat (map (replicate 3) "hello")
"hhheeellllllooo"
The composition of concat and map can be abbreviated as concatMap (this is a library function, not a language feature).
Prelude> concatMap (replicate 3) "hello"
"hhheeellllllooo"
So your function becomes
mult n s = concatMap (replicate n) s
For extra brevity, write this in point-free style as
mult = concatMap . replicate
There are many ways to achieve the same effect as you would with a loop in other languages, and larsmans has shown you one way, using map. Another common way is with recursion. You already know what to do with the first character, so you can recurse through the list like so:
multiply n [] = []
multiply n (x:xs) = replicate n x ++ multiply n xs
larsmans has explained how replicate works. For your homework, maybe you're not supposed to use library functions like replicate, so you can replace the call to replicate with your own version.
Another way based on monadic's nature of list.
You'd like to apply a function to each element of a list.
To do this just bind the list to the function, like this
# "hello" >>= replicate 3
Or,
# let f = flip (>>=) . replicate
To remove flip,
# let g = (=<<) . replicate
You can use applicative functors for this:
import Control.Applicative
multiply n = (<* [1..n])
--- multiply 3 "hello" --> "hhheeellllllooo"
I'm a newbie to Haskell, got stuck on a simple question:
aaa :: [[(Char, Float)]] -> Float -> [[(Char, Float)]]
aaa [[]] a = error "no indata"
aaa [[(a,b)]] c = [[(a, b/c)]]
aaa inD c = ??
How to make it work with more than 1 element in Array?
Ex: aaa [[('a',3)],[('b',4)],[('c',5)]] 4
the result: [[('a',0.75)],[('b',1)],[('c',1.25)]]
Any hint pls, thx!
You can define operations on lists as follows (I give you a simpler example that adds 1 to each list item)
f [] = []
f (head:tail) = (head + 1):(f tail)
I.e. head:tail represents a list; to be more specific, it represents the first list item (head) and the remaining list if we take the first item away (tail). Then, you usually apply your stuff to head and make a recursive call using tail.
Completing your example (without testing) this would yield:
aaa ([(a,b)]:tail) c = [(a, b/c)] : (aaa tail c)
One thing: You are dealing with a list and want to modify each element of the list in a specific way (but each element is transformed the same way). For such occasions, Haskell provides its intrinsic map function, which takes:
the function to transform a list items
the list of items
as parameters and returns the transformed list.
First of all, that [...] stuff denotes lists, not arrays; there is a fundamental difference between those two.
Try to think in terms of fmap :: Functor a => (a -> b) -> f a -> f b. This function takes another function and applies it over a data-structure. You could use it to implement your function. Here is a simple implementation. Try to understand it:
aaa l c = fmap (fmap (fmap (/c))) l