Is it possible to use functions in Haskell parameters? - function

I have seen a few examples of Haskell code that use functions in parameters, but I can never get it to work for me.
example:
-- Compute the nth number of the Fibonacci Sequence
fib 0 = 1
fib 1 = 1
fib (n + 2) = fib (n + 1) + fib n
When I try this, it I get this error:
Parse error in pattern: n + 2
Is this just a bad example? Or do I have to do something special to make this work?

What you have seen is a special type of pattern matching called "n+k pattern", which was removed from Haskell 2010. See What are "n+k patterns" and why are they banned from Haskell 2010? and http://hackage.haskell.org/trac/haskell-prime/wiki/RemoveNPlusK

As Thomas mentioned, you can use View Patterns to accomplish this:
{-# LANGUAGE ViewPatterns #-}
fib 0 = 1
fib 1 = 1
fib ((subtract 2) -> n) = fib (n + 1) + fib n
Due to the ambiguity of - in this case, you'll need to use the subtract function instead.

I'll try to help out, being a total newbie in Haskell.
I believe that the problem is that you can't match (n + 2).
From a logical viewpoint, any argument "n" will never match "n+2", so your third rule would never be selected for evaluation.
You can either rewrite it, like Michael said, to:
fib n = fib (n - 1) + fib (n - 2)
or define the whole fibonnaci in a function using guards, something like:
fibonacci :: Integer -> Integer
fibonacci n
| n == 0 = 0
| (n == 1 || n == 2) = 1
| otherwise = fibonacci(n-1) + fibonacci(n-2)

The pattern matcher is limited to constructor functions. So while you can match the arguments of functions like (:) (the list constrcutor) or Left and Right (constructors of Either), you can't match arithmetic expressions.

I think the fib (n+2) = ... notation doesn't work and is a syntax error. You can use "regular expression" style matching for paramters, like lists or tuples:
foo (x:xs) = ...
where x is the head of the list and xs the remainder of the list or
foo (x:[]) =
which is matched if the list only has one element left and that is stored in x. Even complex matches like
foo ((n,(x:xs)):rg) = ...
are possible. Function definitions in haskell is a complex theme and there are a lot of different styles which can be used.
Another possibility is the use of a "switch-case" scheme:
foo f x | (f x) = [x]
foo _ _ = []
In this case, the element "x" is wrapped in a list if the condition (f x) is true. In the other cases, the f and x parameters aren't interesting and an empty list is returned.
To fix your problem, I don't think any of these are applicable, but why don't throw in a catch-remaining-parameter-values function definition, like:
fib n = (fib (n - 1)) + (fib (n - 2))
Hope this helps,
Oliver

Since (+) is a function, you can't pattern match against it. To do what you wanted, you'd need to modify the third line to read: fib n = fib (n - 1) + fib (n - 2).

Related

Type casting within a recursive function in Haskell

I am learning Haskell and recursion and different types in Haskell is making my brain hurt. I am trying to create a recursive function that will take a 32 bit binary number string and convert it to a decimal number. I think my idea for how the recursion will work is fine but implementing it into Haskell is giving me headaches. This is what I have so far:
bin2dec :: String -> Int
bin2dec xs = ""
bin2dec (x:xs) = bin2dec xs + 2^(length xs) * x
The function is supposed to take a 32 bit number string and then take off the first character of the string. For example, "0100101010100101" becomes "0" and "100101010100101". It then should turn the first character into a integer and multiply it by 2^length of the rest of the string and add it to the function call again. So if the first character in the 32 bit string is "1" then it becomes 1 * 2^(31) + recursive function call.
But, whenever I try to compile it, it returns:
traceProcP1.hs:47:14: error:
* Couldn't match type `[Char]' with `Int'
Expected: Int
Actual: String
* In the expression: ""
In an equation for `bin2dec': bin2dec xs = ""
|
47 | bin2dec xs = ""
| ^^
traceProcP1.hs:48:31: error:
* Couldn't match expected type `Int' with actual type `Char'
* In the second argument of `(+)', namely `2 ^ (length xs) * x'
In the expression: bin2dec xs + 2 ^ (length xs) * x
In an equation for `bin2dec':
bin2dec (x : xs) = bin2dec xs + 2 ^ (length xs) * x
|
48 | bin2dec (x:xs) = bin2dec xs + 2^(length xs) * x
| ^^^^^^^^^^^^^^^^^^
I know this has to do with changing the datatypes, but I am having trouble type casting in Haskell. I have tried type casting x with read and I have tried making guards that will turn the '0' into 0 and '1' into 1, but I am having trouble getting these to work. Any help would be very appreciated.
There is no casting. If you want to convert from one type to another, there needs to be a function with the right type signature to do so. When looking for any function in Haskell, Hoogle is often a good start. In this case, you're looking for Char -> Int, which has several promising options. The first one I see is digitToInt, which sounds about right for you.
But if you'd rather do it yourself, it's quite easy to write a function with the desired behavior, using pattern matching:
bit :: Char -> Int
bit '0' = 0
bit '1' = 1
bit c = error $ "Invalid digit '" ++ [c] ++ "'"

OCaml Power Function

I am trying to write Ocaml power function but i get an error . Here is my code below.
let rec power x n =
if n = 0 then 1
else x * power (x n-1)
Error: This expression has type int
This is not a function; it cannot be applied.
Your recursive call to power is parenthesized incorrectly. You want this:
power x (n - 1)
The parse for what you have would be: power ((x n) - 1). In other words, as the compiler is telling you, it tries to apply x as if it were a function.

Operator overloading in Isabelle

I want to use the nat type in Isabelle but I want to overload some existing definitions like for example addition. I wrote the following code:
theory Prueba
imports Main HOL
begin
primrec suma::"nat ⇒ nat ⇒ nat" where
"suma 0 n = 0" |
"suma (Suc x) n = 0"
no_notation suma (infix "+" 65)
value "2 + (1 :: nat)"
I tried to overload addition with a new definition that always outputs 0. However when I evaluate 2 + (1 :: nat) I get "Suc (Suc (Suc 0))" :: "nat", which means Isabelle is still using the plus definition from Nat. How can I get it to use my new definition of +?
Thank you
Your must use no_notation to remove the default plus-syntax which comes from the plus type class of the Groups theory.
no_notation Groups.plus_class.plus (infixl "+" 65)
Then you can use
notation suma (infixl "+" 65)
to add your own syntax.
(I have never tried to override such basic parts of the definitions. I guess it might lead to strange situations – especially for other people trying to work with your theory afterwards.)

Binary to decimal - prolog

I found this on stack: reversible "binary to number" predicate
But I don't understand
:- use_module(library(clpfd)).
binary_number(Bs0, N) :-
reverse(Bs0, Bs),
binary_number(Bs, 0, 0, N).
binary_number([], _, N, N).
binary_number([B|Bs], I0, N0, N) :-
B in 0..1,
N1 #= N0 + (2^I0)*B,
I1 #= I0 + 1,
binary_number(Bs, I1, N1, N).
Example queries:
?- binary_number([1,0,1], N).
N = 5.
?- binary_number(Bs, 5).
Bs = [1, 0, 1] .
Could somebody explain me the code
Especialy this : binary_number([], _, N, N). (The _ )
Also what does library(clpfd) do ?
And why reverse(Bs0, Bs) ? I took it away it still works fine...
thx in advance
In the original, binary_number([], _, N, N)., the _ means you don't care what the value of the variable is. If you used, binary_number([], X, N, N). (not caring what X is), Prolog would issue a singleton variable warning. Also, what this predicate clause says is that when the first argument is [] (the empty list), then the 3rd and 4th arguments are unified.
As explained in the comments, use_module(library(clpfd)) causes Prolog to use the library for Constraint Logic Programming over Finite Domains. You can also find lots of good info on it via Google search of "prolog clpfd".
Normally, in Prolog, arithmetic expressions of comparison require that the expressions be fully instantiated:
X + Y =:= Z + 2. % Requires X, Y, and Z to be instantiated
Prolog would evaluate and do the comparison and yield true or false. It would throw an error if any of these variables were not instantiated. Likewise, for assignment, the is/2 predicate requires that the right hand side expression be fully evaluable with specific variables all instantiated:
Z is X + Y. % Requires X and Y to be instantiated
Using CLPFD you can have Prolog "explore" solutions for you. And you can further specify what domain you'd like to restrict the variables to. So, you can say X + Y #= Z + 2 and Prolog can enumerate possible solutions in X, Y, and Z.
As an aside, the original implementation could be refactored a little to avoid the exponentiation each time and to eliminate the reverse:
:- use_module(library(clpfd)).
binary_number(Bin, N) :-
binary_number(Bin, 0, N).
binary_number([], N, N).
binary_number([Bit|Bits], Acc, N) :-
Bit in 0..1,
Acc1 #= Acc*2 + Bit,
binary_number(Bits, Acc1, N).
This works well for queries such as:
| ?- binary_number([1,0,1,0], N).
N = 10 ? ;
no
| ?- binary_number(B, 10).
B = [1,0,1,0] ? ;
B = [0,1,0,1,0] ? ;
B = [0,0,1,0,1,0] ? ;
...
But it has termination issues, as pointed out in the comments, for cases such as, Bs = [1|_], N #=< 5, binary_number(Bs, N). A solution was presented by #false which simply modifies the above helps solve those termination issues. I'll reiterate that solution here for convenience:
:- use_module(library(clpfd)).
binary_number(Bits, N) :-
binary_number_min(Bits, 0,N, N).
binary_number_min([], N,N, _M).
binary_number_min([Bit|Bits], N0,N, M) :-
Bit in 0..1,
N1 #= N0*2 + Bit,
M #>= N1,
binary_number_min(Bits, N1,N, M).

Defining a Racket Function?

I'm supposed to define the function n! (N-Factorial). The thing is I don't know how to.
Here is what I have so far, can someone please help with this? I don't understand the conditionals in Racket, so an explanation would be great!
(define fact (lambda (n) (if (> n 0)) (* n < n)))
You'll have to take a good look at the documentation first, this is a very simple example but you have to understand the basics before attempting a solution, and make sure you know how to write a recursive procedure. Some comments:
(define fact
(lambda (n)
(if (> n 0)
; a conditional must have two parts:
; where is the consequent? here goes the advance of the recursion
; where is the alternative? here goes the base case of the recursion
)
(* n < n))) ; this line is outside the conditional, and it's just wrong
Notice that the last expression is incorrect, I don't know what it's supposed to do, but as it is it'll raise an error. Delete it, and concentrate on writing the body of the conditional.
The trick with scheme (or lisp) is to understand each little bit between each set of brackets as you build them up into more complex forms.
So lets start with the conditionals. if takes 3 arguments. It evaluates the first, and if that's true, if returns the second, and if the first argument is false it returns the third.
(if #t "some value" "some other value") ; => "some value"
(if #f "some value" "some other value") ; => "some other value"
(if (<= 1 0) "done" "go again") ; => "go again"
cond would work too - you can read the racket introduction to conditionals here: http://docs.racket-lang.org/guide/syntax-overview.html#%28part._.Conditionals_with_if__and__or__and_cond%29
You can define functions in two different ways. You're using the anonymous function approach, which is fine, but you don't need a lambda in this case, so the simpler syntax is:
(define (function-name arguments) result)
For example:
(define (previous-number n)
(- n 1))
(previous-number 3) ; => 2
Using a lambda like you have achieves the same thing, using different syntax (don't worry about any other differences for now):
(define previous-number* (lambda (n) (- n 1)))
(previous-number* 3) ; => 2
By the way - that '*' is just another character in that name, nothing special (see http://docs.racket-lang.org/guide/syntax-overview.html#%28part._.Identifiers%29). A '!' at the end of a function name often means that that function has side effects, but n! is a fine name for your function in this case.
So lets go back to your original question and put the function definition and conditional together. We'll use the "recurrence relation" from the wiki definition because it makes for a nice recursive function: If n is less than 1, then the factorial is 1. Otherwise, the factorial is n times the factorial of one less than n. In code, that looks like:
(define (n! n)
(if (<= n 1) ; If n is less than 1,
1 ; then the factorial is 1
(* n (n! (- n 1))))) ; Otherwise, the factorial is n times the factorial of one less than n.
That last clause is a little denser than I'd like, so lets just work though it down for n = 2:
(define n 2)
(* n (n! (- n 1)))
; =>
(* 2 (n! (- 2 1)))
(* 2 (n! 1))
(* 2 1)
2
Also, if you're using Racket, it's really easy to confirm that it's working as we expect:
(check-expect (n! 0) 1)
(check-expect (n! 1) 1)
(check-expect (n! 20) 2432902008176640000)