Udar
Udar

Reputation: 85

How to use the argument of a function in a high order function in Haskell

I'm sorry if the title was misleading but I'm not even sure what is my question. I have the following exercise:

We call x a fix point of a function f if f x==x (i.e. f maps x to itself). Write a function fixpoint which accepts a function f :: Integer -> Integer and returns the smallest non-negative integer x which is a fix point of f.

So far all I could think off was:

fixpoint :: (a -> a) -> a

fixpoint f = min [f x | x<-[0..n], f x == x ]

but it is obviously flawed as the n is out of nowhere.

I've tried other things too but they were obvious mistakes.

What is a possible solution to this exercise? I'm new to Haskell and I don't even know how to think about that problem.

Upvotes: 1

Views: 85

Answers (1)

Karl Bielefeldt
Karl Bielefeldt

Reputation: 49148

There are other ways to solve it, but expanding on your idea, you can use [0..] to create an infinite list, so you don't need the n. Then you can't take the min of an infinite list, because it will never complete, but since your list counts up, the smallest one will be the first one, so you can use head:

fixpoint f = head [f x | x <- [0..], f x == x]

Upvotes: 5

Related Questions