Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- GeneralFoldDavidYoung.hs
- generalFold :: ((i,o) -> Either o (i,o)) -> (i,o) -> o
- generalFold fn initial = let Left result = go initial in result
- where go x = fn x >>= go
- sum5 = generalFold transition ([1..5],0)
- where
- transition (list,acc) =
- if list == [] then Left acc
- else Right (tail list,(head list)+acc)
- product5 = generalFold transition ([1..5],1)
- where
- transition (list,acc) =
- if list == [] then Left acc
- else Right (tail list,(head list)*acc)
- vectorToMatrix :: [Double] -> Int -> [[Double]]
- vectorToMatrix vector nColumns = generalFold transition (vector, [])
- where
- transition (info, acc)
- | n < 0 = Left acc
- | otherwise = Right (take n info, drop n info : acc)
- where n = length info - nColumns
- matrix3x3 = vectorToMatrix [1..9] 3
- -- Now, if you want to keep the last state of the input, use this:
- generalFold2 :: ((i,o) -> Either (i,o) (i,o)) -> (i,o) -> (i,o)
- generalFold2 fn initial = let Left result = go initial in result
- where go x = fn x >>= go
- vectorToMatrix2 :: [Double] -> Int -> ([Double],[[Double]])
- vectorToMatrix2 vector nColumns = generalFold2 transition (vector, [])
- where
- transition (info, acc)
- | n < 0 = Left (info,acc)
- | otherwise = Right (take n info, drop n info : acc)
- where n = length info - nColumns
- matrix2 = vectorToMatrix2 [1..10] 3
- -- 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