(問1)
def foldl(func, obj, lst): if lst: return foldl(func, func(obj, lst[0]), lst[1:]) else: return obj def plus(num1, num2): return num1 + num2 def mySum(lst): return foldl(plus, lst[0], lst[1:])
・例
mySum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
(問2)
def foldl(func, obj, lst): if lst: return foldl(func, func(obj, lst[0]), lst[1:]) else: return obj def large(num1, num2): if num1 >= num2: return num1 else: return num2 def myMax(lst): return foldl(large, lst[0], lst[1:])
・例
myMax([34, 55, 77, 1, 2, 3, 4, 100, 98])
(問3)
def foldr(func, lst, obj): if lst: return func(lst[0], foldr(func, lst[1:], obj)) else: return obj def myApply(func, obj): return func(obj) def plus5(num): return num + 5 def times10(num): return num * 10 def divide2(num): return num / 2 def plus5_times10_divide2(num): funcList = [plus5, times10, divide2] funcList.reverse() return foldr(myApply, funcList, num)
・例
plus5_times10_divide2(5)
(参考)
def makeProceduce(lst): lst.reverse() return lambda num: foldr(myApply, lst, num)
・例
divide2_plus5_times10 = makeProceduce([divide2, plus5, times10]) divide2_plus5_times10(4)
いくつか考えてみた (問1)高階関数と再帰関数を必ず使って数値を要素とするリストの要素の総和を求める関数を書け。ただし高階関数を使うという要件と再帰関数を使うという要件は同...
Objective Camlを使ってみたよ! 問3はわからなかった! let rec map f ls = match ls with hd::tl -> f hd (map f tl) | [] -> 0inlet plus x y= x + yinlet rec iter f n ls= match ls with hd::tl -> (iter f (f n hd) tl) | _ -> n...