ITeye博客

一段很有代数味道的代码

诺铁 · 2011-06-27 18:46 · 编程 · 编程语言 · Markdown

一段很有代数味道的代码

来自haskell 99题 http://haskell.org/haskellwiki/99_questions/21_to_28

 

--Insert an element at a given position into a list.

insertAt :: a -> [a] -> Int -> [a]            

 

我本来的写法是

insertAt x xs pos = let ss = splitAt pos xs
                             in fst ss ++ [x] ++ snd ss

 

答案里的写法很妙

insertAt x xs pos = let (ys,zs) = splitAt pos xs
                    in ys ++ [x] ++ zs

 

我的思想仍然有命令式的味道,没想到还有这么"代数式"的写法。haskell里的“let"绝对就是数学里的“设“ ,太妙了

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。