Can functions be used in Haskell parameters?

I saw some Haskell code examples 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, I get this error:

  Parse error in pattern: n + 2 

Is this just a bad example? Or do I need to do something special to make this work?

+4
source share
6 answers

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

+13
source

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 - in this case you will need to use the subtract function.

+3
source

I will try to help as a newbie to Haskell.

I believe the problem is that you cannot match (n + 2). Logically, any argument ā€œnā€ will never match ā€œn + 2ā€, so your third rule will never be selected for evaluation.

You can either rewrite it, as Michael said, to:

 fib n = fib (n - 1) + fib (n - 2) 

or define the entire fibonacci in a function using the guards, for example:

 fibonacci :: Integer -> Integer fibonacci n | n == 0 = 0 | (n == 1 || n == 2) = 1 | otherwise = fibonacci(n-1) + fibonacci(n-2) 
+2
source

Layout template is limited to design functions . Therefore, if you can match arguments of functions like (:) (constrcutor list) or Left and Right ( Either constructors), you cannot match arithmetic expressions.

+2
source

I think the fib (n+2) = ... notation does not work and is a syntax error. You can use the regex style match for parameters, such as lists or tuples:

 foo (x:xs) = ... 

where x is the head of the list and xs is the rest of the list or

 foo (x:[]) = 

which matches if the list has only one item on the left and which is stored in x. Even difficult matches like

 foo ((n,(x:xs)):rg) = ... 

are possible. Function definitions in haskell is a complex topic, and there are many different styles that you can use.

Another possibility is to use a switch-case scheme:

 foo fx | (fx) = [x] foo _ _ = [] 

In this case, the element "x" is wrapped in a list if condition (fx) true. In other cases, the parameters f and x are not interesting and an empty list is returned.

To fix your problem, I do not think that any of them is applicable, but why not use the function definition of the value of the remainder of the remainder parameter, for example:

 fib n = (fib (n - 1)) + (fib (n - 2)) 

Hope this helps,

Oliver

+2
source

Since (+) is a function, you cannot match a template with it. To do what you want, you need to change the third line as follows: fib n = fib (n - 1) + fib (n - 2) .

+1
source

Source: https://habr.com/ru/post/1398254/


All Articles