5.2 vector: 建立和使用vector的各種變體,5.2vector

來源:互聯網
上載者:User

5.2 vector: 建立和使用vector的各種變體,5.2vector
Clojure練習-5.組合資料類型

“用100個函數來操作一個資料結構比10個函數操作10個資料結構要好很多。基於一個統一的資料結構,我們可以構建出一系列的小函數,這些小函數又可以組合起來形成一個強大的系統。而為不同的資料結構編寫不同的函數,在根本上就削減了複用的可能。” —— [ Alan Perlis ]

  • Clojure練習-5組合資料類型
    • 組合資料類型
      • 2 vector 建立和使用vector的各種變體
        • 已知
        • 解1
        • 測試
        • 解2
        • 測試

5. 組合資料類型5.2 vector: 建立和使用vector的各種變體

實現一個函數:已知 一個二維方陣,
輸入: 某點位置
返回: 某點的所有鄰接位置(不包括對角線方向)。

已知
(def matrix  "二維方陣"  [[1 2 3] [4 5 6] [7 8 9]])(doc matrix); 取值(get-in matrix [1 2]) ;=> 6; 取值-遍曆取值(map #(get-in matrix %)  '([1 2])) ;=> (6)(map #(get-in matrix %)  '([1 0] [0 1])) ;=>  (4 2); x,y分別相加(map +  [0 0] [-1 0]) ;=> (-1 0); x,y分別相加 - 遍曆(def Δ [[-1 0] [1 0] [0 -1] [0 1]])(map #(map +  [0 0] %)  Δ) ;=> ((-1 0) (1 0) (0 -1) (0 1)); 使用filter(doc filter)(filter #(< % 3) (range 10)) ;=> (0 1 2)
解1
;;版本1(defn neighbors   "在二維方陣中尋找某點鄰接位置  輸入:   size 表示 二位方陣的邊長   xy   表示 某點   Δ    表示 相對於xy的距離  返回: 如 ((1 0) (0 1))  "  ([size xy] (neighbors [[-1 0] [1 0] [0 -1] [0 1]] size xy))  ([Δ size xy]   (filter (fn [an-xy] (every? #(< -1 % size) an-xy)) ;filter的實參1           '((-1 0) (1 0) (0 -1) (0 1)) ;filter的實參2     )   )  )
測試
;;測試(neighbors 3 [0 0]);=> ((1 0) (0 1))
解2
;;版本2(defn neighbors  "在二維方陣中尋找某點鄰接位置  輸入:   size 表示 二位方陣的邊長   xy   表示 某點   Δ    表示 相對於xy的距離  返回: 如 ((1 0) (0 1))  "  ([size xy] (neighbors [[-1 0] [1 0] [0 -1] [0 1]] size xy))  ([Δ size xy]   (filter (fn [an-xy] (every? #(< -1 % size) an-xy)) ;filter的實參1           (map #(map +  [0 0] %) Δ) ;filter的實參2     )   )  )
測試
;;測試(neighbors 3 [0 0]);=> ((1 0) (0 1))(map #(get-in matrix %) (neighbors 3 [0 0])); => (4 2)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.