I started to learn functional programming for my assigment, I try to count, how many times compares if statement is proper i mean I want to put n++ after the command x > maxTail for display to last value of n
maxList :: (Ord a) => [a] -> a
maxList [x] = x
maxList (x:xs)
| x > maxTail = x
| otherwise = maxTail
where maxTail = maxList xs
Don't try to solve problems in one language the way you would in another language.
In Haskell values are immutable, don't go trying to get a for loop with mutable value ( a
in your case).
Giving an example the other way, I might print the numbers 1 to N in Haskell using traverse_ print [1..n]
. How would that look in C? First write a linked list library. Then write a lazy iterator that can make a linked list until some predicate (equal to n). Then write a higher order function that takes a function pointer and traverses the iterator. Finally iterate over the linked list to print my numbers to standard out. Obviously there are other solutions in C, but if you're asking for a direct translation that's what you get.
So don't ask "how to x++" - there is no direct translation of x++ into Haskell. Instead try to solve, and ask for help on, the higher level task such as counting the number of times an element is greater than all following elements in the list.
First, there is a mistake in your type signature. What you want to return is a number, not just whatever Ord
type being fed into the function. For example, String
is a member of the Ord
typeclass, but you wouldn't want to return a String
.
func :: (Ord a, Num b) => [a] -> b
Second, you need to recurse on the elements looking at two elements at a time. The trick to this is to have two base cases: one for the empty list, and one for a list with only one element:
func [] = 0
func [_] = 0
Once you have those two elements, the rest almost writes itself: is the condition true? if so, add 1 to the recursion; otherwise, just recurse.
func (x:y:xs) --Pattern match on two elements at a time
| x < y = 1 + func (y:xs)
| otherwise = func (y:xs)
One other way to do it is to use higher-order functions. This way, you can decompose the problem into sequential steps:
This translates as:
f xs = length $ filter (\(a, b) -> a < b) $ zip xs $ (tail xs)
-- | |-----------------------| |----------------|
-- | | step 1
-- | step 2
-- step 3
As you can see, functional programming takes completely different routes to problem-solving than imperative programming. This is why sometimes things just don't translate or correspond from one paradigm to another.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.