3 ms·
Haskell - fib (Just n) Nothing = Just (fibs !! n) fib Nothing (Just x) = let (n, x') = head (filter (\(_,y) -> y >= x) (enumerate fibs)) in if x == x'
by ctaylor001 12y ago
Haskell -
fib (Just n) Nothing = Just (fibs !! n)
fib Nothing (Just x) = let (n, x') = head (filter (\(_,y) -> y >= x) (enumerate fibs))
in if x == x' then Just n else Nothing
fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
enumerate = zip [0..]
I think that should work! It's a bit undefined what happens if you supply both arguments, or neither. It would be better to use Either Integer Integer as the input instead of a pair of Maybe Integer.
Of course there's always the LogicT monad if you want to do it "properly".
- segmondy 12y agothe same prolog problem is defined for what happens when you supply both arguments, if the statement is true it will eval to true, if it is false, it will eval to false. if neither, it will generate all possible solutions, one at a time. :-use_module(library(clpq)). fib_aux(N, A, Sum,, F) :- { N = 0, F = 1}; { N = 1, F = 1}; { N >= 2, N1 = N - 1, Acc = Sum, NewSum = A + Sum, F = F1 + Acc, F1 >= N1 % to not run infinitly for unsatisfiable question clp_fib(N, 4). }, fib_aux(N1, Acc, NewSum, F1). fib(N, F) :- fib_aux(N, 0, 1, F).