List of concatenations using foldl ', foldr

I am studying Haskell right now and am having the following problem:

I want to rewrite the ++ function using foldl 'and foldr. I did this with foldr:

myConcat xs ys = foldr (:) ys xs

I can't do this using foldl '. I read at RealWorldHaskell that foldr is useful for this kind of thing. Ok, but can I write the ++ equivalent using foldl? Can someone show me how I can do this (if it can be done ... The book says nothing about it) ...

Is a Haskell type mechanism an obstacle to this? Every time I tried, I got an error like ...

+3
source share
5 answers

, , , - foldr foldl':

myConcat xs ys = foldl' (:) ys xs

( Hugs REPL):

ERROR - Type error in application
*** Expression     : foldl' (:) xs ys
*** Term           : (:)
*** Type           : a -> [a] -> [a]
*** Does not match : [a] -> a -> [a]

, ( ) [a] a . , , (:), .

Haskell , : flip. , flip

flip :: (a -> b -> c) -> (b -> a -> c)
flip f y x = f x y

flip , ( "" ) . , (:) a -> [a] -> [a], , flip (:) [a] -> a -> [a], foldl'.

flip, :

myConcat xs ys = foldl' (flip (:)) ys xs

, foldl' (a -> b -> c) -> a -> [b] -> c

[1..5] [6..10], [5,4,3,2,1,6,7,8,9,10], . , . reverse myConcat:

myConcat xs ys = foldl' (flip (:)) ys (reverse xs)

, Haskell: , () . , , . , ( , foldr foldl'), . , , .

PS: Haskell, , . , , . , Haskell.

+8

: , , , .

foldl:

  • .

, , , . , - , - . , , [ , ),

> foldl (\x y -> y:x) [1, 2, 3] [4, 5, 6]
[6,5,4,1,2,3]

, . ; foldl - -, .

+9

, foldr ( ++) , foldl . foldl foldr: http://www.haskell.org/haskellwiki/Foldl_as_foldr

: foldr foldl:

foldr :: (b -> a -> a) -> a -> [b] -> a
foldr f a bs =
  foldl (\g b x -> g (f b x)) id bs a

, (++) foldl

+4
data [] a = ... | a : [a]
(:) :: a -> [a] -> [a]

(:) op -.

a :: Char
b :: Char
c :: [Char]

a:[b] ok

a:b

a:c .

foldr (:) foldl (:), .

+3

foldl, foldr

foldl:

show $ (\xs ys -> foldl­ (\s e -> e:s ) ys (reve­rse xs)) [1,2]­ [3,4]
+2
source

All Articles