Posts

Showing posts with the label Haskell

[Haskell] [Oz] Function that computes the permutation of a list

Mozart Oz Programming Language declare fun {Permutation L} case L of nil then [nil] [] H|T then {FoldR {Map {Permutation T} fun {$ X} % Inser H into all position IntFrom in fun lazy {IntFrom K} K|{IntFrom K+1} end {Map {List.take {IntFrom 0} {List.length X}+1} fun {$ Pos} {FoldR X (fun {$ J K} case K of nil then nil [] S#I then if I \= Pos-1 then {Append [J] S}#(1+I) else {Append [H J] S}#(1+I) end end end) ({List.drop [H] Pos}#0) }.1 end} end } fun {$ X Y} {Append X Y} end nil } end end %{Browse {Permutation [a]}} % shows [[a]] %{Browse {Permutation nil}} % shows [nil] {Browse {Permutation [a b c]}} % shows [[c b a] [c a b] [a c b] % [b c a] [b a c] [a b c]] Haskell Programming Language -- function that computes the permutations of a list -- permutation ["a","b...

[Haskell] [Oz] Oz function that insert element to all possible positions in a list

function that insert X to all possible positions in the list L. Mozart Oz Programming Language declare fun {AllInsert X L} IntFrom in fun lazy {IntFrom K} K|{IntFrom K+1} end {Map {List.take {IntFrom 0} {List.length L}+1} fun {$ Pos} {FoldR L (fun {$ Z Y} case Y of nil then nil [] S#I then if I \= Pos-1 then {Append [Z] S}#(1+I) else {Append [X Z] S}#(1+I) end end end) ({List.drop [X] Pos}#0) }.1 end} end {Browse {AllInsert 10 [a b c d]}} %shows [a b c d 10] [a b c 10 d] %[a b 10 c d] [a 10 b c d] %[10 a b c d]] Haskell Programming Language -- function that inserts an element at all possible positions in a list allInsert :: a -> [a] -> [[a]] allInsert x [] = [[x]] allInsert x xs = map f [0..(length xs)] where f s = insert x s xs -- allInsert "x" ["a","b","c","d","e...

[Oz] [Haskell] Function that inserts element to a given position in a list

Below are example code in Oz and Haskell for the function that inserts an element at a given position in a list. The position should be counted from the end of the list. Mozart Oz Programming Language declare fun {Insert A Pos L} {FoldR L (fun {$ X Y} case Y of nil then nil [] S#I then if I \= Pos-1 then {Append [X] S}#(1+I) else {Append [A X] S}#(1+I) end end end) ({List.drop [A] Pos}#0)}.1 end {Browse {Insert 10 0 [a b c d e]}} %shows [a b c d e 10] Haskell Programming Language module Main where insert :: a -> Int -> [a] -> [a] insert x n [] = [] insert x n xs = f ++ [x] ++ drop (length xs - n) xs where f = (take (length xs - n) xs) -- insert "x" 1 ["a","b","c","d","e"] References: http://www.haskell.org/ghc/docs/6.12.1/html/libraries/base/src/Data-List.html#insert http://defowl.blogspot.com/2007/04/coding-in-haskell.html