Drkcore

10 07 2010 R Tweet

Rでfoldlとfoldr

Rにおける高階関数はCommon Higher-Order Functions in Functional Programming Languagesにあるように一通りそろっている

Reduce uses a binary function to successively combine the elements of a given vector and a possibly given initial value. Filter extracts the elements of a vector for which a predicate (logical) function gives true. Find and Position give the first or last such element and its position in the vector, respectively. Map applies a function to the corresponding elements of given vectors. Negate creates the negation of a given function.

foldl,foldrも簡単

foldl <- function(f,x,i){Reduce(f,x,i)}
foldr <- function(f,x,i){Reduce(f,x,i,right=TRUE)}

実行してみる

> foldl("-",list(1,2,3),1) # ((1-1)-2)-3
[1] -5
> foldr("-",list(1,2,3),1) # 1-(2-(3-1))
[1] 1

あとRの高階関数は大文字で始める規則にでもなってんのかな?

ProductName Rの基礎とプログラミング技法
U.リゲス
シュプリンガー・ジャパン(株) / ¥ 3,675 ()
通常1~4週間以内に発送

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021