In Elm is there a way to pattern match the arguments of a function to multiple definitions like in Haskell?
Example from Haskell:
factorial :: Int ->
factorial 0 = 1
factorial n = n * factorial (n - 1)
There is no equivalent of that syntax in Elm.
The easiest way to achieve similar behavior would be using pattern matching with case statement.
Please consider the following example:
factorial : Int -> Int
factorial n =
case n of
0 ->
1
_ ->
n * factorial (n - 1)
The _ from the example above serves as a wildcard to match any pattern, in this case, it's any integer different from 0
Related
needing some help (if possible) in how to count the amount of times a recursive function executes itself.
I don't know how to make some sort of counter in OCaml.
Thanks!
Let's consider a very simple recursive function (not Schroder as I don't want to do homework for you) to calculate Fibonacci numbers.
let rec fib n =
match n with
| 0 | 1 -> 1
| _ when n > 0 -> fib (n - 2) + fib (n - 1)
| _ -> raise (Invalid_argument "Negative values not supported")
Now, if we want to know how many times it's been passed in, we can have it take a call number and return a tuple with that call number updated.
To get each updated call count and pass it along, we explicitly call fib in let bindings. Each time c shadows its previous binding, as we don't need that information.
let rec fib n c =
match n with
| 0 | 1 -> (1, c + 1)
| _ when n > 0 ->
let n', c = fib (n - 1) (c + 1) in
let n'', c = fib (n - 2) (c + 1) in
(n' + n'', c)
| _ -> raise (Invalid_argument "Negative values not supported")
And we can shadow that to not have to explicitly pass 0 on the first call.
let fib n = fib n 0
Now:
utop # fib 5;;
- : int * int = (8, 22)
The same pattern can be applied to the Schroder function you're trying to write.
You can create a reference in any higher scope like so
let counter = ref 0 in
let rec f ... =
counter := !counter + 1;
... (* Function body *)
If the higher scope happens to be the module scope (or file top-level scope) you should omit the in
You can return a tuple (x,y) where y you increment by one for each recursive call. It can be useful if your doing for example a Schroder sequence ;)
I'm very new to functional programming. I'm struggling using recursion instead of for loop. Here's what I have so far.
let max_factor n =
let rec loop k =
if k >= n then []
else
begin
if k < n && n % k = 0 then
k :: loop(k+1)
end
my plan is to insert the ones into a list and then find the largest from the list. But I have a feeling I'm doing it wrong. With functional programming, is it always like "going around" or am I just a bad at this? is my approach way off? Can someone please guide me how I should approach this simple problem...
The equivalent to your java code would be
let max_factor (n : int) : int =
let rec loop i =
if i < 2 then 1
else if n mod i = 0 then i
else loop (i-1)
in loop (n / 2);; (* you don't want to start at n, which would trivially divide n *)
How should I alter the factorial recursion, to calculate only the odd or only the double elements of the factorial?For example if:
multiplyOdds(4)
the result should return 1*3*5*7 =105
I know how recursion works, I just need a bit of help which approach I should use.
Your function multiplyOdds(n) needs to multiply the first n odd numbers? Given that the nth odd number is equal to 2 * n - 1, you can easily write a recursive solution like the one below in Haskell:
multiplyOdds :: Int -> Int
multiplyOdds n = multiplyOddsTail n 1
multiplyOddsTail :: Int -> Int -> Int
multiplyOddsTail n acc = case n of
1 -> acc
n -> multiplyOddsTail (n - 1) (acc * (n * 2 - 1))
I'm sure there's a way to do this elegantly in SML but I'm having difficulty keeping track of the number of iterations (basically the number of times my function has been called).
I'm trying to write a function that evaluates to a pair of numbers, one for the floor of the answer and the other for the remainder. So if you called:
divmod(11, 2), you'd get (5, 1) back.
Here's what I have so far:
divmod(number : int, divisor : int) =
if number < divisor then
(number, count)
else
divmod(number - divisor, divisor);
Obviously, I haven't set up my count variable so it won't compile but that's the idea of the algorithm. All that's left is initializing count to 0 and being able to pass it between recursive calls. But I'm only allowed the two parameters for this function.
I can, however, write auxiliary functions.
Thoughts?
If SML has support for nested functions you could do like this:
divmod(number : int, divisor : int) =
_divmod(n : int, d : int, count : int) =
if n < d then
(count, n)
else
_divmod(n - d, d, count + 1)
_divmod(number, divisor, 0)
Personally, I like the fact that SML isn't a pure functional language. Keeping track of function calls is naturally done via side effects (rather than explicitly passing a counter variable).
For example, given a generic recursive Fibonacci:
fun fib 0 = 0
| fib 1 = 0
| fib n = fib(n-2) + fib(n-1);
You can modify it so that every time it is called it increments a counter as a side effect:
counter = ref 0;
fun fib 0 = (counter := !counter + 1; 0)
| fib 1 = (counter := !counter + 1; 1)
| fib n = (counter := !counter + 1; fib(n-2) + fib(n-1));
You can use this directly or wrap it up a bit:
fun fibonacci n = (
counter :=0;
let val v = fib n
in
(!counter,v)
end);
With a typical run:
- fibonacci 30;
val it = (2692537,832040) : int * int
(Which, by the way, shows why this version of the Fibonacci recursion isn't very good!)
I'm having some issues with my prime number checker in F#. It doesn't seem to give the right results so I'm guessing I've screwed up the logic somewhere but I can't figure out where. The implementation is a simple brute forcing one so the logic isn't complicated and I've implemented similiar solutions using for loops in imperative languages before.
let rec isPrime iterator (n : int) =
match iterator with
| 1 -> isPrime (iterator + 1) n
| a when a = n -> isPrime (iterator + 1) n
| _ -> match n % iterator = 0 with
| true -> false
| false -> isPrime (iterator + 1) n
As you already figured out in the comments, the problem is that the function should terminate and say true when the iterator reaches n. You can actually make it faster just by iterating up to square root of n or at least n/2 because by the time you reach n/2, you know it will be a prime.
This kind of logic seems to be easier to write using if rather than match - although you can easily fix it by fixing the case in match, I'd probably write something like:
let rec isPrime iterator (n : int) =
if iterator = n / 2 then true
elif iterator = 1 then isPrime (iterator + 1) n
elif n % iterator = 0 then false
else isPrime (iterator + 1) n
Also, you might not want to expose the iterator parameter to the user - you can write the code using a nested function which calls the loop starting with iterator = 2 (and then you don't need the iterator = 1 case at all):
let isPrime (n : int) =
let rec loop iterator =
if iterator = n/2 then true
elif n % iterator = 0 then false
else loop (iterator + 1)
loop 2