totem3
2/11/2012 - 11:42 PM

プログラミングHaskell第7章練習問題(´;ω;`)ブワッ

プログラミングHaskell第7章練習問題(´;ω;`)ブワッ

-- 8, 9がわかりましぇん(´;ω;`)ブワッ

import Data.Char

--1
--[f x|x <- xs, p x]
-- 
--(map f).(filter p)

--2
myAll :: (a -> Bool) -> [a] -> Bool
myAll f xs = ((foldr (&&) True).(map f)) xs

myAny :: (a -> Bool) -> [a] -> Bool
myAny f xs = ((foldr (||) False).(map f)) xs

myTakeWhile :: (a -> Bool) -> [a] -> [a]
myTakeWhile f xs = take (tl (map f xs)) xs

myDropWhile :: (a -> Bool) -> [a] -> [a]
myDropWhile f xs = drop (tl (map f xs)) xs

tl :: [Bool] -> Int
tl [] = 0
tl (b:bs) = if b == True then 1 + tl bs else 0

--3
myMap :: (a -> b) -> [a] -> [b]
myMap f xs = foldr (\x -> (:) (f x)) [] xs

myFilter :: (a -> Bool) -> [a] -> [a]
myFilter p xs = foldr (\x -> (++) (if p x then [x] else [])) [] xs

--4
dec2int :: [Int] -> Int
dec2int = foldl (\x y -> 10 * x + y) (0)

--5
compose :: [a -> a] -> (a -> a)
compose = foldr (.) id

{-
sumsqreven = compare [sum, map (^2), filter even]
composeの定義が上だとすると、
sumの型が[a] -> a で型が他と異なるから?
-}

--6
myCurry :: ((a, b) -> c) -> a -> b -> c
myCurry f x y = f (x, y)

myUncurry :: (a -> b -> c) -> ((a, b) -> c)
myUncurry f p = f (fst p) (snd p)

--7
unfold p h t x | p x       = []
               | otherwise = h x : unfold p h t (t x)

type Bit = Int

chop8 :: [Bit] -> [[Bit]]
chop8 bits = unfold (len) (take 8) (drop 8) bits
             where len xs = length xs < 8

chop9 :: [Bit] -> [[Bit]]
chop9 bits = unfold (len) (take 9) (drop 9) bits
             where len xs = length xs < 9

myMap2 :: (a -> b) -> [a] -> [b]
myMap2 f xs = unfold (len) (f.head) (tail) xs
              where len xs = length xs == 0

myIterate :: (a -> a) -> a -> [a]
myIterate f x = unfold (\x -> False) (f) (f) x