ネタ記録庫/Haskell

totally insane? 純粋関数的に1パスで木の全てのノードを最小値に書き換える †

http://obfuscatedcode.wordpress.com/2008/02/16/functional-pearl-trees/

data Tree a = Leaf a          -- The leaf holds data of any type.
            | Branch (Tree a) (Tree a) deriving (Show)


replaceMin :: Tree Int -> Tree Int
replaceMin t = let (t', m) = rpMin (t, m) in t'

rpMin :: (Tree Int, Int) -> (Tree Int, Int)
rpMin (Leaf a, m) = (Leaf m, a)
rpMin (Branch l r, m) = let (l', ml) = rpMin (l, m)
                            (r', mr) = rpMin (r, m)
                   in (Branch l' r', ml `min` mr)

OCaml版 ? †

open Lazy
type 'a tree = Leaf of 'a | Branch of 'a tree * 'a tree

let rec rp_min = function
| Leaf a, m -> Leaf m, a
| Branch (l,r), m -> let l', ml = rp_min (l, m) in
                     let r', mr = rp_min (r, m) in
     Branch (l', r'), lazy (min (force ml) (force mr))

let replace_min t =
  let rec t'_m () = rp_min (t, lazy (force (snd (t'_m())))) in
  fst (t'_m())

ちょっと似ている話 breadth-first numbering by Chris Okasaki †

StateT †

これは、permutationを返す関数:

permutation' :: [[Int]] -> Int -> [Int] -> [[Int]]
permutation' result 0 _ = result
permutation' result n cand =
    do a <- cand
       permutation' (map (a:) result) (n-1) [x|x<-cand,x/=a]

使い方

permutation' [[]] [1,2,3] 2

のように使う。

これをStateTを使ってわざと分かりにくくしてみる:

permutation :: [[Int]] -> Int -> StateT [Int] [] [[Int]]
permutation result 0 = return result
permutation result n =
    do cand <- get
       a <- lift cand
       put [x|x<-cand,x/=a]
       permutation (map (a:) result) (n-1) 

これは

runStateT (permutation [[]] 2) [1,2,3]

のように使う。

  • Thx. 勉強になります。 -- げんま? 2007-04-24 (火) 12:45:05
  • 使い方は、permutation' [[]] 2 [1,2,3] ではないでしょうか? <-元職業プログラマ -- 2008-07-10 (木) 22:46:11

HaskellでWIKI &dagger;

書いてみました。いまのところ日本語は使えません。 http://icecs.ice.nuie.nagoya-u.ac.jp/~h043078b/wiki.cgi

History of Haskell &dagger;

HaskellでOS。 &dagger;

http://www.cse.ogi.edu/~hallgren/House/ -- 源馬? 2006-07-04 (火) 16:16:05

The Evolution of a Haskell Programmer &dagger;

The Evolution of a Haskell Programmer かなりハイレベルにバカやってる感じ

  • バカだ〜!fold関数使うまではわかるけど、その後が!まだまだまだまだ続くし。 -- げんま? 2006-08-12 (土) 10:35:43
  • インタプリタを作って階乗計算させたり,型クラスを使ったテクニックなんかもあるので分かると結構良いかも。 -- けいご? 2006-08-12 (土) 15:27:52

Haskell 型クラス、MPTC, Fundeps と type improvement by けいご &dagger;

トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS