Haskell: Scan Through a List and Apply A Different Function for Each Element

前端 未结 4 1945
我寻月下人不归
我寻月下人不归 2021-02-06 11:43

I need to scan through a document and accumulate the output of different functions for each string in the file. The function run on any given line of the file depends on what i

4条回答
  •  无人共我
    2021-02-06 12:06

    If you have only 2 alternatives, using Either might be a good idea. In that case combine your functions, map the list, and use lefts and rights to get the results:

    import Data.Either
    
    -- first sample function, returning String
    f1 x = show $ x `div` 2
    
    -- second sample function, returning Int
    f2 x = 3*x+1
    
    -- combined function returning Either String Int
    hotpo x = if even x then Left (f1 x) else Right (f2 x)
    
    xs = map hotpo [1..10] 
    -- [Right 4,Left "1",Right 10,Left "2",Right 16,Left "3",Right 22,Left "4",Right 28,Left "5"]
    
    lefts xs 
    -- ["1","2","3","4","5"]
    
    rights xs
    -- [4,10,16,22,28]
    

提交回复
热议问题