Advertisement
jckuri

GeneralFoldDavidYoung.hs

Nov 28th, 2013
761
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- GeneralFoldDavidYoung.hs
  2.  
  3. generalFold :: ((i,o) -> Either o (i,o)) -> (i,o) -> o
  4. generalFold fn initial = let Left result = go initial in result
  5.  where go x = fn x >>= go
  6.  
  7. sum5 = generalFold transition ([1..5],0)
  8.  where
  9.   transition (list,acc) =
  10.    if list == [] then Left acc
  11.    else Right (tail list,(head list)+acc)
  12.    
  13. product5 = generalFold transition ([1..5],1)
  14.  where
  15.   transition (list,acc) =
  16.    if list == [] then Left acc
  17.    else Right (tail list,(head list)*acc)
  18.  
  19. vectorToMatrix :: [Double] -> Int -> [[Double]]
  20. vectorToMatrix vector nColumns = generalFold transition (vector, [])
  21.  where
  22.   transition (info, acc)
  23.    | n < 0 = Left acc
  24.    | otherwise = Right (take n info, drop n info : acc)
  25.    where n = length info - nColumns
  26.    
  27. matrix3x3 = vectorToMatrix [1..9] 3
  28.  
  29. -- Now, if you want to keep the last state of the input, use this:
  30.  
  31. generalFold2 :: ((i,o) -> Either (i,o) (i,o)) -> (i,o) -> (i,o)
  32. generalFold2 fn initial = let Left result = go initial in result
  33.  where go x = fn x >>= go
  34.  
  35. vectorToMatrix2 :: [Double] -> Int -> ([Double],[[Double]])
  36. vectorToMatrix2 vector nColumns = generalFold2 transition (vector, [])
  37.  where
  38.   transition (info, acc)
  39.    | n < 0 = Left (info,acc)
  40.    | otherwise = Right (take n info, drop n info : acc)
  41.    where n = length info - nColumns
  42.    
  43. matrix2 = vectorToMatrix2 [1..10] 3
  44. -- matrix2 == ([1.0],[[2.0,3.0,4.0],[5.0,6.0,7.0],[8.0,9.0,10.0]])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement