clojure - 简单的map函数返回nils列表

时间:2014-10-14 14:55:29

标签: clojure

此函数获取文件列表,并且应该返回艺术家列表:

(defn get-artists [files]
    (map #(.get-artist (->Mp3 %)) files))

这里是代码的其余部分:

(ns musicdb.filesystem
    (:use [green-tags.core]))

(import '(java.io.File) '(java.net.url) '(java.io))
(require '[clojure.string :as str])

(defn get-files [search-path]
  (let [directory (clojure.java.io/file search-path)
        files (file-seq directory)
        fonly (filter #(.isFile %) files)]
   (map #(last (str/split (.toString %) #"/")) fonly)))

(defprotocol MusicFile
    (get-artist [this])
    (get-song [this])
    (get-album [this]))


(defrecord Mp3 [filename]
    MusicFile
    (get-artist [this]
        (:artist (get-all-info filename)))
    (get-song [this]
        (:title (get-all-info filename)))
    (get-album [this]
        (:album (get-all-info filename))))

以下是我的测试:

(ns musicdb.core-test
  (:require [clojure.test :refer :all]
            [musicdb.core :refer :all]
            [musicdb.filesystem :refer :all]
            [clojure.pprint :refer :all]
            ))

(deftest test_0
  (testing "getFiles returns valid result"
    (is (> (count (get-files "/home/ls/books/books")) 50))))

(deftest test_1
  (testing "check for file included"
    (is (some #{"02 Backlit.mp3"} (get-files "/home/ls/Musik")))))

(deftest test_2
    (testing "creating music file record"
        (let [myfile (->Mp3 "/home/ls/Musik/Panopticon/02 Backlit.mp3")]
            (is (= "Isis" (.get-artist myfile)))
            (is (= "Backlit" (.get-song myfile))))))
(deftest test_3
    (testing "testing get-artists"
    (let [artists (get-artists (get-files "/home/ls/Musik"))
        ]
        (is (> (count artists) 10)))))

(deftest test_4
    (testing "testing get-artists check for artist"
        (let [artists (get-artists (get-files "/home/ls/Musik"))
            ]
            (is (some #{"Isis"} artists))))) ;artists is [nil nil nil ...]

从这个测试中,只有最后一个失败,返回一个nils列表。

如果要重现,请务必在leiningen project.clj中包含green-tags依赖项:

[green-tags "0.3.0-alpha"]  

1 个答案:

答案 0 :(得分:1)

您的get-files函数未返回文件的完整路径,因此get-all-info只返回nil(https://github.com/DanPallas/green-tags/blob/master/src/green_tags/core.clj#L59https://github.com/DanPallas/green-tags/blob/master/src/green_tags/core.clj#L120的组合)。

这是一个有效的简单示例:

(map (comp :artist get-all-info)
     (filter #(.isFile %)
             (file-seq (java.io.File. "/home/vema/Downloads/mp3"))))
;=> ("Yo Yo Honey Singh (DJJOhAL.Com)")

(幽默?)免责声明:MP3不应该作为我的音乐品味的一个例子,它只是我在网上找到的第一个免费MP3。