Advertisement
jckuri

GeneralFold.hs

Nov 28th, 2013
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- I just came up with a generalFold.
  2. -- Is there something similar in Haskell?
  3.  
  4. generalFold :: ((info,acc) -> Maybe (info,acc)) -> (info,acc) -> (info,acc)
  5. generalFold transition duple =
  6.  let newDupleMaybe = transition duple
  7.  in case newDupleMaybe of
  8.   Nothing -> duple
  9.   Just newDuple -> generalFold transition newDuple
  10.  
  11. sum10 = generalFold transition ([1..10],0)
  12.  where
  13.   transition (info,acc) =
  14.    if (length info) <= 0 then Nothing
  15.    else Just (tail info,(head info)+acc)
  16.  
  17. product10 = generalFold transition ([1..10],1)
  18.  where
  19.   transition (info,acc) =
  20.    if (length info) <= 0 then Nothing
  21.    else Just (tail info,(head info)*acc)
  22.  
  23. vectorToMatrix :: [Double] -> Int -> [[Double]]
  24. vectorToMatrix vector nColumns =
  25.  let (info,acc) = generalFold transition (vector,[])
  26.  in acc
  27.  where
  28.   transition (info,acc) =
  29.    if n < 0 then Nothing
  30.    else Just (take n info,(drop n info):acc)
  31.    where n = length info - nColumns
  32.    
  33. matrix3x3 = vectorToMatrix [1..9] 3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement